From 0b5421edc2f6bb4a788cb0b93b93f59ceee72059 Mon Sep 17 00:00:00 2001 From: Zeev Diukman Date: Sat, 8 Mar 2025 17:51:15 +0000 Subject: [PATCH] 4 --- reverseproxy.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/reverseproxy.go b/reverseproxy.go index 26a93a9..d742173 100644 --- a/reverseproxy.go +++ b/reverseproxy.go @@ -28,7 +28,7 @@ func New(ctx context.Context, host string) *ReverseProxy { targetQuery := target.RawQuery r.URL.Scheme = target.Scheme r.URL.Host = target.Host - r.URL.Path, r.URL.RawPath = joinURLPath(target, r.URL) + r.URL.Path, r.URL.RawPath = JoinURLPath(target, r.URL) if targetQuery == "" || r.URL.RawQuery == "" { r.URL.RawQuery = targetQuery + r.URL.RawQuery } else { @@ -45,11 +45,11 @@ func (revereProxy *ReverseProxy) SetContext(ctx context.Context) { revereProxy.Context = ctx } func (revereProxy *ReverseProxy) DirectorFunc(df func(jup JoinURLPathFunc) DirectorFunc) { - d := df(joinURLPath) + d := df(JoinURLPath) revereProxy.Director = d } -func singleJoiningSlash(a, b string) string { +func SingleJoiningSlash(a, b string) string { aslash := strings.HasSuffix(a, "/") bslash := strings.HasPrefix(b, "/") switch { @@ -61,9 +61,9 @@ func singleJoiningSlash(a, b string) string { return a + b } -func joinURLPath(a, b *url.URL) (path, rawpath string) { +func JoinURLPath(a, b *url.URL) (path, rawpath string) { if a.RawPath == "" && b.RawPath == "" { - return singleJoiningSlash(a.Path, b.Path), "" + return SingleJoiningSlash(a.Path, b.Path), "" } // Same as singleJoiningSlash, but uses EscapedPath to determine // whether a slash should be added @@ -86,3 +86,12 @@ type JoinURLPathFunc func(*url.URL, *url.URL) (string, string) // type SingleJoiningSlashFunc func(string, string) string type DirectorFunc func(*http.Request) + +func StripPrefix(r *http.Request, prefix string) *http.Request { + newPath := strings.TrimPrefix(r.URL.Path, prefix) + if newPath == "" { + newPath = "/" + } + r.URL.Path = newPath + return r +}