feat: initial commit
This commit is contained in:
30
middleware/allowed_hosts.go
Normal file
30
middleware/allowed_hosts.go
Normal 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...))
|
||||
}
|
||||
}
|
56
middleware/rewrite_hosts.go
Normal file
56
middleware/rewrite_hosts.go
Normal 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))
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user