namespace DTLib.Web.Routes; public class SimpleRouter : IRouter { /// route for any url that doesn't have its own handler public RouteHandler? DefaultRoute { get; set; } private readonly Dictionary _routes = new(); private readonly ILogger _logger; public SimpleRouter(ILogger logger) { _logger = logger; } public void MapRoute(string url, HttpMethod method, RouteHandler route) => _routes.Add($"{url}:{method}", route); public void MapRoute(string url, HttpMethod method, Func> route) => MapRoute(url, method, new DelegateRouteHandler(route)); public async Task Resolve(HttpListenerContext ctx) { string? requestPath = ctx.Request.Url?.AbsolutePath; if (string.IsNullOrEmpty(requestPath)) requestPath = "/"; if (!_routes.TryGetValue($"{requestPath}:{ctx.Request.HttpMethod}", out var route)) route = DefaultRoute; HttpStatusCode status; if (route == null) { _logger.LogWarn(nameof(SimpleRouter), $"couldn't resolve request path {requestPath}"); status = HttpStatusCode.NotFound; } else status = await route.HandleRequest(ctx); ctx.Response.StatusCode = (int)status; await ctx.Response.OutputStream.FlushAsync(); ctx.Response.OutputStream.Close(); return status; } }