70 lines
2.3 KiB
C#
70 lines
2.3 KiB
C#
namespace Uwaa.HTTP.Routing;
|
|
|
|
/// <summary>
|
|
/// Selects one of multiple possible routers.
|
|
/// </summary>
|
|
public class Router : RouterBase
|
|
{
|
|
public record Route(string? Key, RouterBase Router);
|
|
|
|
public readonly List<Route> Routes = new List<Route>();
|
|
|
|
public override HttpMethod Method => HttpMethod.Any;
|
|
|
|
public override int Arguments => 0;
|
|
|
|
protected override async Task<HttpResponse?> GetResponseInner(HttpRequest req, HttpClientInfo info, ArraySegment<string> path)
|
|
{
|
|
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, info, route.Key == null || path.Count == 0 ? path : path[1..]);
|
|
if (resp != null)
|
|
return resp;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds a route to the router on the given sub path.
|
|
/// </summary>
|
|
public void Add(string? key, RouterBase router) => Routes.Add(new Route(key, router));
|
|
|
|
/// <summary>
|
|
/// Adds a route to the router.
|
|
/// </summary>
|
|
public void Add(RouterBase router) => Add(null, router);
|
|
|
|
/// <summary>
|
|
/// Adds an endpoint to the router on the given sub path.
|
|
/// </summary>
|
|
public void Add(string? key, FuncEndpointDelegateAsync func) => Routes.Add(new Route(key, new FuncEndpoint(func)));
|
|
|
|
/// <summary>
|
|
/// Adds a wildcard endpoint to the router.
|
|
/// </summary>
|
|
public void Add(FuncEndpointDelegateAsync func) => Add(null, func);
|
|
|
|
/// <summary>
|
|
/// Adds an endpoint to the router on the given sub path.
|
|
/// </summary>
|
|
public void Add(string? key, FuncEndpointDelegate func) => Add(key, (req, info) => Task.FromResult(func(req, info)));
|
|
|
|
/// <summary>
|
|
/// Adds a wildcard endpoint to the router.
|
|
/// </summary>
|
|
public void Add(FuncEndpointDelegate func) => Add(null, func);
|
|
|
|
/// <summary>
|
|
/// Adds a static response to the router on the given sub path.
|
|
/// </summary>
|
|
public void Add(string? key, HttpResponse response) => Routes.Add(new Route(key, new StaticEndpoint(response)));
|
|
|
|
/// <summary>
|
|
/// Adds a wildcard static response to the router.
|
|
/// </summary>
|
|
public void Add(HttpResponse response) => Add(null, response);
|
|
}
|