Compare commits

...

4 commits

Author SHA1 Message Date
uwaa
b12616420b make nested router slugs work 2024-11-14 02:39:12 +00:00
uwaa
5447f37cea add code to read request body 2024-11-14 02:33:12 +00:00
uwaa
e0ae00c523 clean 2024-11-14 02:31:06 +00:00
uwaa
ba79856131 allow function endpoints to be used w/ any method 2024-11-14 02:30:55 +00:00
4 changed files with 24 additions and 5 deletions

View file

@ -76,6 +76,11 @@ public sealed class HttpRequest
/// </summary>
public bool IsWebsocket => Headers.TryGetValue("Upgrade", out string? connection) && connection.Equals("websocket", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// The total declared size of the request body, in bytes.
/// </summary>
public int ContentLength => Headers.TryGetValue("Content-Length", out string? contentLengthStr) && int.TryParse(contentLengthStr, out int contentLength) ? contentLength : 0;
internal HttpRequest(HttpServer server, TcpClient client, Stream stream, IPEndPoint endpoint)
{
Server = server;
@ -374,6 +379,16 @@ public sealed class HttpRequest
return false;
}
/// <summary>
/// Reads the entire request body. Only call this once.
/// </summary>
public async Task<string> ReadBody()
{
byte[] data = new byte[ContentLength];
int count = await ReadBytes(data);
return Encoding.UTF8.GetString(data, 0, count);
}
}
/// <summary>

View file

@ -89,7 +89,11 @@ public partial class FileEndpoint : RouterBase
{
mime = GuessMIMEType(fileInfo.Extension);
}
return !File.Exists(assetPath) ? null : (HttpResponse)new HttpContent(mime, await File.ReadAllBytesAsync(assetPath));
if (!File.Exists(assetPath))
return null;
return new HttpContent(mime, await File.ReadAllBytesAsync(assetPath));
}
/// <summary>

View file

@ -15,7 +15,7 @@ public class FuncEndpoint : RouterBase
Function = function;
}
public override HttpMethod Method => HttpMethod.GET;
public override HttpMethod Method => HttpMethod.Any;
public override int Arguments => 0;

View file

@ -13,16 +13,16 @@ public class Router : RouterBase
public override HttpMethod Method => HttpMethod.Any;
public override int Arguments => 1;
public override int Arguments => 0;
protected override async Task<HttpResponse?> GetResponseInner(HttpRequest req, ArraySegment<string> path)
{
string next = path[0];
string next = path.Count == 0 ? string.Empty : path[0];
foreach (Route route in Routes)
{
if (route.Key == next || route.Key == null)
{
HttpResponse? resp = await route.Router.GetResponse(req, route.Key == null ? path : path[1..]);
HttpResponse? resp = await route.Router.GetResponse(req, route.Key == null || path.Count == 0 ? path : path[1..]);
if (resp != null)
return resp;
}