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