using System.IO; using System.Net; using Webserver.FileCache; namespace Webserver.UrlHandlers { public class StaticHandler : AbsHandler { private readonly AbstractCache cache; private readonly string datapath; private readonly bool logMissingFiles; public StaticHandler (string _filePath, AbstractCache _cache, bool _logMissingFiles, string _moduleName = null) : base (_moduleName) { datapath = $"{_filePath}{(_filePath [^1] == '/' ? "" : "/")}"; cache = _cache; logMissingFiles = _logMissingFiles; } public override void HandleRequest (RequestContext _context) { string fn = _context.RequestPath.Remove (0, urlBasePath.Length); byte[] content = cache.GetFileContent ($"{datapath}{fn}"); if (content != null) { _context.Response.ContentType = MimeType.GetMimeType (Path.GetExtension (fn)); _context.Response.ContentLength64 = content.Length; _context.Response.OutputStream.Write (content, 0, content.Length); } else { _context.Response.StatusCode = (int) HttpStatusCode.NotFound; if (logMissingFiles) { Log.Warning ($"[Web] Static: FileNotFound: \"{_context.RequestPath}\" @ \"{datapath}{fn}\""); } } } } }