From 1eb208cba36bc6da981ea8c6dac311a16a0b2418 Mon Sep 17 00:00:00 2001 From: Timerix Date: Sun, 23 Mar 2025 02:36:47 +0500 Subject: [PATCH] HttpMethod --- DTLib.Web/DTLib.Web.csproj | 2 +- DTLib.Web/HttpMethod.cs | 15 +++++++++++++++ DTLib.Web/Routes/SimpleRouter.cs | 16 +++++++--------- 3 files changed, 23 insertions(+), 10 deletions(-) create mode 100644 DTLib.Web/HttpMethod.cs diff --git a/DTLib.Web/DTLib.Web.csproj b/DTLib.Web/DTLib.Web.csproj index 62feff1..fd9145c 100644 --- a/DTLib.Web/DTLib.Web.csproj +++ b/DTLib.Web/DTLib.Web.csproj @@ -2,7 +2,7 @@ DTLib.Web - 1.1.2 + 1.2.0 Timerix HTTP Server with simple routing GIT diff --git a/DTLib.Web/HttpMethod.cs b/DTLib.Web/HttpMethod.cs new file mode 100644 index 0000000..475f999 --- /dev/null +++ b/DTLib.Web/HttpMethod.cs @@ -0,0 +1,15 @@ +namespace DTLib.Web; + +/// +public enum HttpMethod +{ + GET, + POST, + PUT, + DELETE, + PATCH, + HEAD, + OPTIONS, + TRACE, + CONNECT +} \ No newline at end of file diff --git a/DTLib.Web/Routes/SimpleRouter.cs b/DTLib.Web/Routes/SimpleRouter.cs index a291056..8d808e4 100644 --- a/DTLib.Web/Routes/SimpleRouter.cs +++ b/DTLib.Web/Routes/SimpleRouter.cs @@ -3,9 +3,9 @@ namespace DTLib.Web.Routes; public class SimpleRouter : IRouter { /// route for base url - public RouteHandler? HomePageRoute = null; + public RouteHandler? HomePageRoute { get; set; } /// route for any url that doesn't have its own handler - public RouteHandler? DefaultRoute = null; + public RouteHandler? DefaultRoute { get; set; } private readonly Dictionary _routes = new(); @@ -15,12 +15,11 @@ public class SimpleRouter : IRouter { _logger = logger; } - - public void MapRoute(string url, Func> route) - => MapRoute(url, new DelegateRouteHandler(route)); + public void MapRoute(string url, HttpMethod method, RouteHandler route) => _routes.Add($"{url}:{method}", route); - public void MapRoute(string url, RouteHandler route) => _routes.Add(url, route); + public void MapRoute(string url, HttpMethod method, Func> route) + => MapRoute(url, method, new DelegateRouteHandler(route)); public async Task Resolve(HttpListenerContext ctx) { @@ -28,9 +27,8 @@ public class SimpleRouter : IRouter RouteHandler? route; if(HomePageRoute != null && requestPath == "/") route = HomePageRoute; - else if (_routes.TryGetValue(requestPath, out var routeDelegate)) - route = routeDelegate; - else route = DefaultRoute; + else if (!_routes.TryGetValue($"{requestPath}:{ctx.Request.HttpMethod}", out route)) + route = DefaultRoute; HttpStatusCode status; if (route == null)