feat: add a strip-base-prefix option (#655)
* style: fix formatting in .air.toml and installation.mdx * feat: add --strip-base-prefix flag to modify request paths when forwarding Closes: #638 * refactor: apply structpacking (betteralign) * fix: add validation for strip-base-prefix and base-prefix configuration * fix: improve request path handling by cloning request and modifying URL path * chore: remove integration tests as they are too annoying to debug on my system
This commit is contained in:
parent
60ba8e9557
commit
3b3080d497
9 changed files with 155 additions and 7 deletions
27
lib/http.go
27
lib/http.go
|
|
@ -134,6 +134,32 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
s.mux.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {
|
||||
if !s.opts.StripBasePrefix || s.opts.BasePrefix == "" {
|
||||
return r
|
||||
}
|
||||
|
||||
basePrefix := strings.TrimSuffix(s.opts.BasePrefix, "/")
|
||||
path := r.URL.Path
|
||||
|
||||
if !strings.HasPrefix(path, basePrefix) {
|
||||
return r
|
||||
}
|
||||
|
||||
trimmedPath := strings.TrimPrefix(path, basePrefix)
|
||||
if trimmedPath == "" {
|
||||
trimmedPath = "/"
|
||||
}
|
||||
|
||||
// Clone the request and URL
|
||||
reqCopy := r.Clone(r.Context())
|
||||
urlCopy := *r.URL
|
||||
urlCopy.Path = trimmedPath
|
||||
reqCopy.URL = &urlCopy
|
||||
|
||||
return reqCopy
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {
|
||||
if s.next == nil {
|
||||
redir := r.FormValue("redir")
|
||||
|
|
@ -158,6 +184,7 @@ func (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {
|
|||
).ServeHTTP(w, r)
|
||||
} else {
|
||||
requestsProxied.WithLabelValues(r.Host).Inc()
|
||||
r = s.stripBasePrefixFromRequest(r)
|
||||
s.next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue