63 lines
1.8 KiB
C#
63 lines
1.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace ln.http.route;
|
|
|
|
public class HttpRoute
|
|
{
|
|
protected HttpRouterDelegate _routerDelegate;
|
|
|
|
public HttpMethod HttpMethod { get; protected set; }
|
|
public Regex Route { get; protected set; }
|
|
|
|
public HttpRoute(HttpMethod httpMethod, string route, HttpRouterDelegate routerDelegate)
|
|
:this(httpMethod, route)
|
|
{
|
|
_routerDelegate = routerDelegate;
|
|
}
|
|
|
|
protected HttpRoute(HttpMethod httpMethod, string route)
|
|
{
|
|
HttpMethod = httpMethod;
|
|
Route = route is string ? new Regex(route) : null;
|
|
}
|
|
|
|
public bool TryRoute(HttpRequestContext httpRequestContext, string routePath)
|
|
{
|
|
bool matched = false;
|
|
|
|
if (
|
|
(HttpMethod == HttpMethod.ANY) ||
|
|
(HttpMethod == httpRequestContext.Request.Method)
|
|
)
|
|
{
|
|
if (Route is null)
|
|
{
|
|
matched = true;
|
|
}
|
|
else
|
|
{
|
|
Match match = Route.Match(routePath);
|
|
if (match.Success)
|
|
{
|
|
foreach (Group group in match.Groups.Values)
|
|
if (group.Success)
|
|
httpRequestContext.SetParameter(group.Name, group.Value);
|
|
|
|
routePath = routePath.Substring(match.Length);
|
|
matched = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (matched)
|
|
return _routerDelegate(httpRequestContext, routePath) && (httpRequestContext.Response is not null);
|
|
|
|
return false;
|
|
}
|
|
|
|
public override string ToString() => $"[HttpRoute HttpMethod={HttpMethod} Route={Route}]";
|
|
} |