add http methods

This commit is contained in:
uwaa 2024-10-28 06:56:48 +00:00
parent 2dacb80d49
commit 3dd2c79b21

View file

@ -22,6 +22,9 @@ public class Router : IRouter
//Must be fast
foreach (Endpoint endpoint in Endpoints)
{
if (endpoint.Method != HttpMethod.Any && request.Method != endpoint.Method)
continue;
if (!endpoint.CheckMatch(path))
continue;
@ -41,7 +44,7 @@ public class Router : IRouter
/// </summary>
/// <param name="path">The full path to the endpoint.</param>
/// <param name="handler">The function to call to produce a response.</param>
public void Add(string path, EndpointHandlerAsync handler)
public void Add(HttpMethod method, string path, EndpointHandlerAsync handler)
{
//Runs at startup
string[] spl = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
@ -59,13 +62,13 @@ public class Router : IRouter
pattern[i] = new PathSegment(name, type);
}
Endpoints.Add(new Endpoint(pattern, PathMatchMode.AllowTrailing, handler));
Endpoints.Add(new Endpoint(method, pattern, PathMatchMode.AllowTrailing, handler));
}
/// <inheritdoc cref="Add(string, EndpointHandlerAsync)" />
public void Add(string path, EndpointHandler handler)
public void Add(HttpMethod method, string path, EndpointHandler handler)
{
Add(path, (req, route) => Task.FromResult(handler(req, route)));
Add(method, path, (req, route) => Task.FromResult(handler(req, route)));
}
/// <summary>
@ -73,7 +76,7 @@ public class Router : IRouter
/// </summary>
public void Add(IRouter router)
{
Endpoints.Add(new Endpoint(Array.Empty<PathSegment>(), PathMatchMode.AllowTrailing, (req, route) => router.Handle(req, route.Request)));
Endpoints.Add(new Endpoint(HttpMethod.Any, Array.Empty<PathSegment>(), PathMatchMode.AllowTrailing, (req, route) => router.Handle(req, route.Request)));
}
/// <summary>
@ -126,13 +129,15 @@ public readonly struct RouteMatch
public readonly struct Endpoint
{
public readonly HttpMethod Method;
public readonly PathSegment[] Pattern;
public readonly PathMatchMode MatchMode;
public readonly EndpointHandlerAsync Handler;
public Endpoint(PathSegment[] path, PathMatchMode matchMode, EndpointHandlerAsync handler)
public Endpoint(HttpMethod method, PathSegment[] path, PathMatchMode matchMode, EndpointHandlerAsync handler)
{
Pattern = path;
MatchMode = matchMode;