From f29cea2d55ba8803fef19054510b4c2c186757c5 Mon Sep 17 00:00:00 2001 From: uwaa Date: Mon, 16 Dec 2024 03:52:03 +0000 Subject: [PATCH] http: add FileRecursiveEndpoint --- HTTP/Routing/FileEndpoint.cs | 39 +++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/HTTP/Routing/FileEndpoint.cs b/HTTP/Routing/FileEndpoint.cs index 070d4de..2fe572e 100644 --- a/HTTP/Routing/FileEndpoint.cs +++ b/HTTP/Routing/FileEndpoint.cs @@ -3,7 +3,7 @@ namespace Uwaa.HTTP.Routing; /// -/// Special router which serves static files from the filesystem. +/// Special router which serves static files from a directory in the filesystem. /// public partial class FileEndpoint : RouterBase { @@ -12,7 +12,7 @@ public partial class FileEndpoint : RouterBase return extension switch { ".txt" => new("text", "plain"), - ".htm" or "html" => new("text", "html"), + ".htm" or ".html" => new("text", "html"), ".js" => new("text", "javascript"), ".css" => new("text", "css"), ".csv" => new("text", "csv"), @@ -69,13 +69,18 @@ public partial class FileEndpoint : RouterBase protected override async Task GetResponseInner(HttpRequest req, HttpClientInfo info, ArraySegment path) { - string? asset = path[0]; - if (string.IsNullOrWhiteSpace(asset)) - return null; - + string asset = path[0]; if (FilenameChecker().IsMatch(asset)) return HttpResponse.BadRequest("Illegal chars in asset path"); + return await GetFile(asset); + } + + protected async ValueTask GetFile(string asset) + { + if (asset == "") + asset = "index.html"; + string assetPath = $"{Directory}/{asset}"; FileInfo fileInfo = new FileInfo(assetPath); MIMEType mime; @@ -103,5 +108,25 @@ public partial class FileEndpoint : RouterBase /// /// Returns a regular expression which checks for invalid characters. [GeneratedRegex(@"[^a-zA-Z0-9_\-.()\[\] ]")] - private static partial Regex FilenameChecker(); + protected static partial Regex FilenameChecker(); +} + +/// +/// Special router which serves static files from a directory and its subdirectories. +/// +public partial class FileRecursiveEndpoint : FileEndpoint +{ + public FileRecursiveEndpoint(string directory) : base(directory) + { + } + + protected override async Task GetResponseInner(HttpRequest req, HttpClientInfo info, ArraySegment path) + { + foreach (string pathSeg in path) + if (FilenameChecker().IsMatch(pathSeg)) + return HttpResponse.BadRequest("Illegal chars in asset path"); + + string asset = Path.Combine(path.ToArray()); + return await GetFile(asset); + } }