http: add FileRecursiveEndpoint

This commit is contained in:
uwaa 2024-12-16 03:52:03 +00:00
parent 40459b9ad8
commit f29cea2d55

View file

@ -3,7 +3,7 @@
namespace Uwaa.HTTP.Routing;
/// <summary>
/// Special router which serves static files from the filesystem.
/// Special router which serves static files from a directory in the filesystem.
/// </summary>
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<HttpResponse?> GetResponseInner(HttpRequest req, HttpClientInfo info, ArraySegment<string> 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<HttpContent?> 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
/// </remarks>
/// <returns>Returns a regular expression which checks for invalid characters.</returns>
[GeneratedRegex(@"[^a-zA-Z0-9_\-.()\[\] ]")]
private static partial Regex FilenameChecker();
protected static partial Regex FilenameChecker();
}
/// <summary>
/// Special router which serves static files from a directory and its subdirectories.
/// </summary>
public partial class FileRecursiveEndpoint : FileEndpoint
{
public FileRecursiveEndpoint(string directory) : base(directory)
{
}
protected override async Task<HttpResponse?> GetResponseInner(HttpRequest req, HttpClientInfo info, ArraySegment<string> 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);
}
}