50 lines
1.9 KiB
C#
50 lines
1.9 KiB
C#
using ln.http.exceptions;
|
|
using System.Collections.Generic;
|
|
using System.Net.Http;
|
|
|
|
namespace ln.http.router
|
|
{
|
|
public class VirtualHostRouter
|
|
{
|
|
public HttpRouterDelegate DefaultRoute { get; set; }
|
|
|
|
Dictionary<string, HttpRouterDelegate> virtualHosts = new Dictionary<string, HttpRouterDelegate>();
|
|
|
|
public VirtualHostRouter()
|
|
{
|
|
}
|
|
public VirtualHostRouter(HttpRouterDelegate defaultRoute)
|
|
{
|
|
DefaultRoute = defaultRoute;
|
|
}
|
|
public VirtualHostRouter(IEnumerable<KeyValuePair<string, HttpRouterDelegate>> routes)
|
|
{
|
|
foreach (KeyValuePair<string, HttpRouterDelegate> route in routes)
|
|
virtualHosts.Add(route.Key, route.Value);
|
|
}
|
|
public VirtualHostRouter(HttpRouterDelegate defaultRoute,IEnumerable<KeyValuePair<string, HttpRouterDelegate>> routes)
|
|
:this(routes)
|
|
{
|
|
DefaultRoute = defaultRoute;
|
|
}
|
|
public VirtualHostRouter(VirtualHostRouter source)
|
|
: this(source.virtualHosts) { }
|
|
|
|
public void Add(string hostname,HttpRouterDelegate router) => virtualHosts.Add(hostname, router);
|
|
public void Remove(string hostname) => virtualHosts.Remove(hostname);
|
|
public bool Contains(string hostname) => virtualHosts.ContainsKey(hostname);
|
|
|
|
public bool TryGetValue(string hostname, out HttpRouterDelegate router) => virtualHosts.TryGetValue(hostname, out router);
|
|
|
|
public bool Route(HttpContext httpContext)
|
|
{
|
|
if (virtualHosts.TryGetValue(httpContext.Request.Host, out HttpRouterDelegate virtualHost))
|
|
return virtualHost(httpContext);
|
|
if (DefaultRoute != null)
|
|
return DefaultRoute(httpContext);
|
|
|
|
throw new HttpException(410, string.Format("Gone. Hostname {0} not found on this server.", httpContext.Request.Host));
|
|
}
|
|
}
|
|
}
|