From 2b5d6b6a544c16d24930d0ded504b1762e58bf5a Mon Sep 17 00:00:00 2001 From: Timerix Date: Sun, 23 Mar 2025 01:20:25 +0500 Subject: [PATCH] fixes for ServeFilesRouteHandler --- DTLib.Web/DTLib.Web.csproj | 4 +-- DTLib.Web/Routes/ServeFilesRouteHandler.cs | 31 +++++++++++++--------- DTLib.Web/WebApp.cs | 2 +- 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/DTLib.Web/DTLib.Web.csproj b/DTLib.Web/DTLib.Web.csproj index 75c1a63..62feff1 100644 --- a/DTLib.Web/DTLib.Web.csproj +++ b/DTLib.Web/DTLib.Web.csproj @@ -2,7 +2,7 @@ DTLib.Web - 1.1.1 + 1.1.2 Timerix HTTP Server with simple routing GIT @@ -25,6 +25,6 @@ - + diff --git a/DTLib.Web/Routes/ServeFilesRouteHandler.cs b/DTLib.Web/Routes/ServeFilesRouteHandler.cs index d209c5c..ac3d03b 100644 --- a/DTLib.Web/Routes/ServeFilesRouteHandler.cs +++ b/DTLib.Web/Routes/ServeFilesRouteHandler.cs @@ -7,24 +7,31 @@ public class ServeFilesRouteHandler(IOPath _publicDir, string _homePageUrl = "in if (ctx.Request.HttpMethod != "GET") return HttpStatusCode.BadRequest; - string requestPath = ctx.Request.Url?.AbsolutePath ?? "/"; - if (requestPath == "/") + string requestPath = ctx.Request.Url?.AbsolutePath!; + if (string.IsNullOrEmpty(requestPath) || requestPath == "/") + { requestPath = _homePageUrl; + } + string ext = Path.Extension(requestPath).Str; IOPath filePath = Path.Concat(_publicDir, requestPath); - if (!File.Exists(filePath)) + if (!File.Exists(filePath)) return HttpStatusCode.NotFound; - - string contentType = ext switch + + List<(string key, string val)> headers = ext switch { - "html" => "text/html", - "css" => "text/css", - "js" or "jsx" or "ts" or "tsx" or "map" => "text/javascript", - _ => "binary/octet-stream" + "html" => [("Content-Type", "text/html")], + "css" => [("Content-Type", "text/css")], + "js" or "jsx" or "ts" or "tsx" or "map" => [("Content-Type", "text/javascript")], + _ => + [ + ("Content-Type", "binary/octet-stream"), + ("Content-Disposition", $"attachment filename={filePath.LastName()}") + ] }; - ctx.Response.Headers.Set("Content-Type", contentType); - ctx.Response.Headers.Set("Content-Disposition", "attachment filename=" + filePath.LastName()); - + foreach (var header in headers) + ctx.Response.Headers.Set(header.key, header.val); + var fileStream = File.OpenRead(filePath); ctx.Response.ContentLength64 = fileStream.Length; await fileStream.CopyToAsync(ctx.Response.OutputStream); diff --git a/DTLib.Web/WebApp.cs b/DTLib.Web/WebApp.cs index f8aba8c..d1a83ea 100644 --- a/DTLib.Web/WebApp.cs +++ b/DTLib.Web/WebApp.cs @@ -54,7 +54,7 @@ public class WebApp { _logger.LogInfo(logContext, $"[{ctx.Request.HttpMethod}] {ctx.Request.RawUrl} from {ctx.Request.RemoteEndPoint} ..."); var status = await _router.Resolve(ctx); - _logger.LogInfo(logContext, status); + _logger.LogInfo(logContext, $"{(int)status} ({status})"); } catch (Exception ex) {