feat: initial commit

This commit is contained in:
2023-04-24 19:53:37 +02:00
commit 6854557831
13 changed files with 701 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package middleware
import (
"net/http"
"forge.cadoles.com/Cadoles/go-proxy"
"forge.cadoles.com/Cadoles/go-proxy/wildcard"
)
func FilterHosts(allowedHostPatterns ...string) proxy.Middleware {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if matches := wildcard.MatchAny(r.Host, allowedHostPatterns...); !matches {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
func WithAllowedHosts(allowedHostPatterns ...string) proxy.OptionFunc {
return func(o *proxy.Options) {
o.Middlewares = append(o.Middlewares, FilterHosts(allowedHostPatterns...))
}
}

View File

@ -0,0 +1,56 @@
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))
}
}