60 lines
2.2 KiB
C#
60 lines
2.2 KiB
C#
using ln.http.route;
|
|
using ln.templates;
|
|
using ln.templates.html;
|
|
|
|
namespace ln.http.templates
|
|
{
|
|
public class FileSystemTemplateRouter : HttpRoute, IDisposable
|
|
{
|
|
private HttpRouter _parentRouter;
|
|
private FileSystemTemplateSource _fileSystemTemplateSource;
|
|
|
|
public FileSystemTemplateRouter(HttpRouter parentRouter, string mapPath, string fileSystemPath)
|
|
:this(parentRouter, mapPath, new FileSystemTemplateSource(fileSystemPath))
|
|
{
|
|
}
|
|
|
|
public FileSystemTemplateRouter(HttpRouter parentRouter, string mapPath, FileSystemTemplateSource fileSystemTemplateSource)
|
|
:base(HttpMethod.GET, mapPath)
|
|
{
|
|
_routerDelegate = RouteTemplate;
|
|
_fileSystemTemplateSource = fileSystemTemplateSource;
|
|
|
|
_parentRouter = parentRouter;
|
|
_parentRouter?.Map(this);
|
|
}
|
|
|
|
bool RouteTemplate(HttpRequestContext requestContext, string routePath)
|
|
{
|
|
if (routePath.EndsWith("/"))
|
|
routePath = string.Format("{0}index.html", routePath);
|
|
|
|
if (!routePath.EndsWith(".html"))
|
|
return false;
|
|
|
|
TemplateDocument templateDocument = _fileSystemTemplateSource.GetTemplateByPath(routePath.Substring(1));
|
|
if (templateDocument is null)
|
|
return false;
|
|
|
|
StreamedContent streamedContent = new StreamedContent("text/html");
|
|
requestContext.Response = HttpResponse.OK().Content(streamedContent);
|
|
|
|
RenderContext renderContext = new RenderContext(
|
|
new StreamWriter(streamedContent.ContentStream),
|
|
_fileSystemTemplateSource, new[]
|
|
{
|
|
new KeyValuePair<string, object>("request", requestContext.Request),
|
|
new KeyValuePair<string, object>("response", requestContext.Response),
|
|
new KeyValuePair<string, object>("context", requestContext)
|
|
}
|
|
);
|
|
templateDocument.RenderTemplate(renderContext);
|
|
return true;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_parentRouter?.UnMap(this);
|
|
}
|
|
}
|
|
} |