Files
telemt-api/internal/proxy/reverse.go
T
Denozordec 91f289c647
ci / test (push) Successful in 1m15s
ci / docker (push) Successful in 1m8s
Init
2026-03-29 22:51:02 +07:00

34 lines
842 B
Go

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
}