ln.http/ln.http/FileSystemRouter.cs

120 lines
3.5 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 System.Collections.Generic;
using ln.http.route;
using ln.mime;
namespace ln.http
{
public class FileSystemRouter : HttpRoute
{
private string _rootPath;
public String RootPath
{
get => _rootPath;
private set
{
_rootPath = Path.GetFullPath(value);
}
}
List<string> indexNames = new List<string>();
public String[] IndexNames => indexNames.ToArray();
private HttpRouter _parentRouter;
private MimeTypes _mimeTypes;
public FileSystemRouter(HttpRouter parentRouter, string mapPath, MimeTypes mimeTypes, string fileSystemPath)
:base(HttpMethod.GET, mapPath)
{
_parentRouter = parentRouter;
_parentRouter?.Map(this);
_mimeTypes = mimeTypes;
if (!Directory.Exists(fileSystemPath))
throw new FileNotFoundException();
RootPath = fileSystemPath;
Console.Error.WriteLine("FileSystemRouter created ({0})", RootPath);
AddIndex("index.html");
AddIndex("index.htm");
_routerDelegate = RouteToFileSystem;
}
public FileSystemRouter(string mapPath, MimeTypes mimeTypes, string fileSystemPath)
:this(null, mapPath, mimeTypes, fileSystemPath){}
public FileSystemRouter(string mapPath, string fileSystemPath)
:this(null, mapPath, null, fileSystemPath){}
public FileSystemRouter(MimeTypes mimeTypes, string fileSystemPath)
:this(null, null, mimeTypes, fileSystemPath)
{
}
public FileSystemRouter(string fileSystemPath)
:this(null, null, null, fileSystemPath)
{
}
public void AddIndex(string indexName) => indexNames.Add(indexName);
public void RemoveIndex(string indexName) => indexNames.Remove(indexName);
public bool RouteToFileSystem(HttpRequestContext requestContext, string routePath)
{
string filename = ChooseFile(routePath);
if (filename is null)
return false;
requestContext.Response =
HttpResponse
.OK()
.Content(new FileStream(filename, FileMode.Open, FileAccess.Read));
if (_mimeTypes?.TryGetMimeTypeByExtension(Path.GetExtension(filename), out MimeType mimeType) ?? false)
requestContext.Response.ContentType(mimeType.ToString());
return true;
}
string ChooseFile(string path)
{
string finalPath = Path.Join(_rootPath, path);
if (File.Exists(finalPath))
return finalPath;
if (Directory.Exists(finalPath))
{
foreach (string indexName in indexNames)
{
string indexFileName = Path.Combine(finalPath, indexName);
if (File.Exists(indexFileName))
return indexFileName;
}
}
return null;
}
public void Dispose()
{
_parentRouter?.UnMap(this);
_parentRouter = null;
}
}
}