From ace21031f98f0e7512e39120b5b30b58457efc02 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Tue, 2 May 2023 08:43:45 -0600 Subject: simple handler dispatcher for hostname-based virtual hosting --- handler.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'handler.go') diff --git a/handler.go b/handler.go index bf6a21d..1c2d6dc 100644 --- a/handler.go +++ b/handler.go @@ -64,3 +64,20 @@ func Filter( }) } } + +// VirtualHosts builds a handler which dispatches to site handlers by hostname. +// +// The 'catchall' argument may be used to specify a handler for use when no hostname +// match is found. If the catchall is nil and no match is found, the VirtualHosts +// handler returns a nil response. +func VirtualHosts(hosts map[string]Handler, catchall Handler) Handler { + return HandlerFunc(func(ctx context.Context, request *Request) *Response { + if h := hosts[request.Hostname()]; h != nil { + return h.Handle(ctx, request) + } + if catchall != nil { + return catchall.Handle(ctx, request) + } + return nil + }) +} -- cgit v1.2.3