go-proxy/middleware/rewrite_hosts.go

57 lines
1.0 KiB
Go

package middleware
import (
"net/http"
"net/url"
"sort"
"forge.cadoles.com/Cadoles/go-proxy"
"forge.cadoles.com/Cadoles/go-proxy/util"
"forge.cadoles.com/Cadoles/go-proxy/wildcard"
)
func RewriteHosts(mappings map[string]*url.URL) proxy.Middleware {
patterns := make([]string, len(mappings))
for p := range mappings {
patterns = append(patterns, p)
}
sort.Strings(patterns)
util.Reverse(patterns)
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
var match *url.URL
for _, p := range patterns {
if matches := wildcard.Match(r.Host, p); !matches {
continue
}
match = mappings[p]
break
}
if match == nil {
h.ServeHTTP(w, r)
return
}
r.URL.Host = match.Host
r.URL.Scheme = match.Scheme
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
func WithRewriteHosts(mappings map[string]*url.URL) proxy.OptionFunc {
return func(o *proxy.Options) {
o.Middlewares = append(o.Middlewares, RewriteHosts(mappings))
}
}