This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// NewReverseProxy builds a reverse proxy to target base URL with path rewriting:
|
||||
// stripPrefix (/api/{alias}) + pathPrefix (/v1) + remainder.
|
||||
func NewReverseProxy(target *url.URL, stripPrefix, pathPrefix string, setAuth string) *httputil.ReverseProxy {
|
||||
proxy := httputil.NewSingleHostReverseProxy(target)
|
||||
orig := proxy.Director
|
||||
proxy.Director = func(req *http.Request) {
|
||||
orig(req)
|
||||
p := req.URL.Path
|
||||
if strings.HasPrefix(p, stripPrefix) {
|
||||
rest := strings.TrimPrefix(p, stripPrefix)
|
||||
rest = strings.TrimPrefix(rest, "/")
|
||||
if rest == "" {
|
||||
req.URL.Path = pathPrefix
|
||||
} else {
|
||||
req.URL.Path = pathPrefix + "/" + rest
|
||||
}
|
||||
req.URL.RawPath = ""
|
||||
}
|
||||
if setAuth != "" {
|
||||
req.Header.Set("Authorization", setAuth)
|
||||
}
|
||||
}
|
||||
return proxy
|
||||
}
|
||||
Reference in New Issue
Block a user