~emersion/public-inbox

[PATCH kimchi] allow wildcard sites

Details
Message ID
<20201121012312.49346-1-slowjo@halmen.xyz>
DKIM signature
missing
Download raw message
closes: https://todo.sr.ht/~emersion/kimchi/14
---
This might not be the way you want this implemented, but with my limited
testing it seems to work.
 directives.go | 36 +++++++++++++++++++++++++++++++++++-
 1 file changed, 35 insertions(+), 1 deletion(-)

diff --git a/directives.go b/directives.go
index 96b153c..72a74d4 100644
--- a/directives.go
+++ b/directives.go
@@ -44,6 +44,11 @@ func parseConfig(srv *Server, cfg scfg.Block) error {
 
 func parseSite(srv *Server, dir *scfg.Directive) error {
 	for _, uriStr := range dir.Params {
+		var wild bool
+		if strings.Contains(uriStr, "*.") {
+			uriStr = strings.Replace(uriStr, "*.", "", 1)
+			wild = true
+		}
 		if !strings.Contains(uriStr, "//") {
 			uriStr = "//" + uriStr
 		}
@@ -114,11 +119,40 @@ func parseSite(srv *Server, dir *scfg.Directive) error {
 			}
 		}
 
-		ln.Mux.Handle(pattern, handler)
+		if wild {
+			wildcard.Handle(ln, host, handler)
+		} else {
+			ln.Mux.Handle(pattern, handler)
+		}
 	}
 	return nil
 }
 
+type wildcardHandler map[string]http.Handler
+
+func (w wildcardHandler) Handle(ln *Listener, host string, handler http.Handler) {
+	if len(w) == 0 {
+		ln.Mux.Handle("/", w)
+	}
+	w[host] = handler
+}
+
+func (w wildcardHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
+	if host, _, err := net.SplitHostPort(req.Host); err == nil {
+		for pattern, handler := range w {
+			if strings.HasSuffix(host, "." + pattern) {
+				handler.ServeHTTP(rw, req)
+				return
+			}
+		}
+	}
+	http.NotFound(rw, req)
+}
+
+var wildcard = wildcardHandler{}
+
 type parseBackendFunc func(dir *scfg.Directive) (http.Handler, error)
 
 var backends = map[string]parseBackendFunc{
-- 
2.29.2
Reply to thread Export thread (mbox)