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
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReverseProxyPathRewrite(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/health" {
|
||||
t.Fatalf("path %q", r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
up, _ := url.Parse(srv.URL)
|
||||
rp := NewReverseProxy(up, "/api/main_srv", "/v1", "")
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/main_srv/health", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
rp.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d", rec.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user