ln.http/router/StaticRouter.cs

68 lines
2.0 KiB
C#

// /**
// * File: FileSystemRouter.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using System.IO;
using ln.http.message;
using System.Collections.Generic;
namespace ln.http.router
{
public class StaticRouter : IHttpRouter
{
public String RootPath { get; }
List<string> indexNames = new List<string>();
public String[] IndexNames => indexNames.ToArray();
public StaticRouter(string path)
{
if (!Directory.Exists(path))
throw new FileNotFoundException();
RootPath = Path.GetFullPath(path);
AddIndex("index.html");
AddIndex("index.htm");
}
public void AddIndex(string indexName) => indexNames.Add(indexName);
public void RemoveIndex(string indexName) => indexNames.Remove(indexName);
public HttpResponse Route(string path, HttpRequest httpRequest)
{
string finalPath = Path.Combine(RootPath, path.Substring(1));
if (Directory.Exists(finalPath))
{
foreach (string indexName in indexNames)
{
string indexFileName = Path.Combine(finalPath, indexName);
if (File.Exists(indexFileName))
{
finalPath = indexFileName;
break;
}
}
}
if (File.Exists(finalPath))
{
lock (this)
{
HttpResponse httpResponse = new HttpResponse(httpRequest, new FileStream(finalPath, FileMode.Open));
httpResponse.SetHeader("content-type", MimeTypeMap.GetMimeType(Path.GetExtension(finalPath)));
return httpResponse;
}
}
return null;
}
}
}