95 lines
3.2 KiB
C#
95 lines
3.2 KiB
C#
using System;
|
|
using System.Text.RegularExpressions;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using ln.http.route;
|
|
|
|
namespace ln.http
|
|
{
|
|
public delegate bool HttpRouterDelegate(HttpRequestContext context, string routedPath);
|
|
public delegate bool HttpAuthorizationDelegate(HttpRequestContext httpRequestContext);
|
|
public delegate void HttpFilterDelegate(HttpRequestContext httpRequestContext);
|
|
|
|
|
|
public enum HttpRoutePriority : int { HIGHEST = 0, HIGH = 1, NORMAL = 2, LOW = 3, LOWEST = 4 }
|
|
|
|
public class HttpRouter : HttpRoute, IDisposable
|
|
{
|
|
public event HttpFilterDelegate HttpFilters;
|
|
public event HttpFilterDelegate HttpFixups;
|
|
|
|
private HttpRouter _parentRouter;
|
|
private List<HttpRoute> _routes = new List<HttpRoute>();
|
|
|
|
public HttpRouter()
|
|
:this(HttpMethod.ANY, null)
|
|
{
|
|
_routerDelegate = RouteRequest;
|
|
}
|
|
|
|
public HttpRouter(HttpMethod httpMethod, string mapPath)
|
|
: base(httpMethod, mapPath)
|
|
{
|
|
}
|
|
|
|
public HttpRouter(HttpRouter parentRouter, string mapPath)
|
|
:base(HttpMethod.ANY, mapPath)
|
|
{
|
|
_parentRouter = parentRouter;
|
|
_parentRouter.Map(this);
|
|
}
|
|
|
|
public void Map(HttpRoute httpRoute) => _routes.Add(httpRoute);
|
|
public void UnMap(HttpRoute httpRoute) => _routes.Remove(httpRoute);
|
|
|
|
public void Map(HttpMethod httpMethod, string route, HttpRouterDelegate routerDelegate)
|
|
=> Map(new HttpRoute(httpMethod, route, routerDelegate));
|
|
|
|
|
|
public bool RouteRequest(HttpRequestContext httpRequestContext, string routePath)
|
|
{
|
|
HttpFilters?.Invoke(httpRequestContext);
|
|
|
|
foreach (var httpRoute in _routes)
|
|
{
|
|
if (httpRoute.TryRoute(httpRequestContext, routePath))
|
|
{
|
|
HttpFixups?.Invoke(httpRequestContext);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_parentRouter?.Dispose();
|
|
}
|
|
|
|
public override string ToString() => $"[HttpRouter]";
|
|
|
|
/*private string RegexFromRoute(string route)
|
|
{
|
|
string[] parts = route.Split(new char[] { '/' });
|
|
string[] reparts = parts.Select((part) =>
|
|
{
|
|
if (part.StartsWith(":", StringComparison.InvariantCulture))
|
|
if (part.EndsWith("*", StringComparison.InvariantCulture))
|
|
return string.Format("(?<{0}>[^/]+)(?<_>/.*)?", part.Substring(1, part.Length - 2));
|
|
else
|
|
return string.Format("(?<{0}>[^/]+)", part.Substring(1));
|
|
else if (part.Equals("*"))
|
|
return string.Format("(?<_>.*)");
|
|
else if (part.EndsWith("*", StringComparison.InvariantCulture))
|
|
return string.Format("{0}[^/]+(?<_>/.*)?", part.Substring(0, part.Length-1));
|
|
else
|
|
return string.Format("{0}", part);
|
|
}).ToArray();
|
|
|
|
return string.Format("^{0}/?$", string.Join("/", reparts));
|
|
}*/
|
|
|
|
}
|
|
}
|