// SPDX-License-Identifier: AGPL-3.0-or-later package middleware import ( "net/http" "strings" ) // BasePath strips a configured path prefix from incoming requests so the // router sees paths without the prefix. This enables deployment at both // faves.example.com (basePath="") and example.com/faves (basePath="/faves"). func BasePath(prefix string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { if prefix == "" { return next } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Strip the prefix from the URL path. if strings.HasPrefix(r.URL.Path, prefix) { r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix) if r.URL.Path == "" { r.URL.Path = "/" } // Also update RawPath if present. if r.URL.RawPath != "" { r.URL.RawPath = strings.TrimPrefix(r.URL.RawPath, prefix) if r.URL.RawPath == "" { r.URL.RawPath = "/" } } } next.ServeHTTP(w, r) }) } }