2016-02-26 14:29:53 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
2018-07-31 09:28:03 +00:00
|
|
|
"context"
|
2016-02-26 14:29:53 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-07-31 09:28:03 +00:00
|
|
|
const (
|
|
|
|
// StripPrefixKey is the key within the request context used to
|
|
|
|
// store the stripped prefix
|
|
|
|
StripPrefixKey key = "StripPrefix"
|
|
|
|
// StripPrefixSlashKey is the key within the request context used to
|
|
|
|
// store the stripped slash
|
|
|
|
StripPrefixSlashKey key = "StripPrefixSlash"
|
|
|
|
// ForwardedPrefixHeader is the default header to set prefix
|
|
|
|
ForwardedPrefixHeader = "X-Forwarded-Prefix"
|
|
|
|
)
|
2017-04-16 09:24:26 +00:00
|
|
|
|
2016-02-26 14:29:53 +00:00
|
|
|
// StripPrefix is a middleware used to strip prefix from an URL request
|
|
|
|
type StripPrefix struct {
|
2016-04-06 11:06:31 +00:00
|
|
|
Handler http.Handler
|
|
|
|
Prefixes []string
|
2016-02-26 14:29:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StripPrefix) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2016-04-06 11:06:31 +00:00
|
|
|
for _, prefix := range s.Prefixes {
|
2017-11-21 13:28:03 +00:00
|
|
|
if strings.HasPrefix(r.URL.Path, prefix) {
|
2018-07-31 09:28:03 +00:00
|
|
|
trailingSlash := r.URL.Path == prefix+"/"
|
2017-11-21 13:28:03 +00:00
|
|
|
r.URL.Path = stripPrefix(r.URL.Path, prefix)
|
|
|
|
if r.URL.RawPath != "" {
|
|
|
|
r.URL.RawPath = stripPrefix(r.URL.RawPath, prefix)
|
|
|
|
}
|
2018-07-31 09:28:03 +00:00
|
|
|
s.serveRequest(w, r, strings.TrimSpace(prefix), trailingSlash)
|
2016-04-06 12:30:29 +00:00
|
|
|
return
|
2016-04-06 11:06:31 +00:00
|
|
|
}
|
2016-02-26 14:29:53 +00:00
|
|
|
}
|
2016-04-06 11:06:31 +00:00
|
|
|
http.NotFound(w, r)
|
2016-02-26 14:29:53 +00:00
|
|
|
}
|
2016-03-27 00:05:17 +00:00
|
|
|
|
2018-07-31 09:28:03 +00:00
|
|
|
func (s *StripPrefix) serveRequest(w http.ResponseWriter, r *http.Request, prefix string, trailingSlash bool) {
|
|
|
|
r = r.WithContext(context.WithValue(r.Context(), StripPrefixSlashKey, trailingSlash))
|
|
|
|
r = r.WithContext(context.WithValue(r.Context(), StripPrefixKey, prefix))
|
2017-05-28 03:50:03 +00:00
|
|
|
r.Header.Add(ForwardedPrefixHeader, prefix)
|
2017-05-22 22:44:02 +00:00
|
|
|
r.RequestURI = r.URL.RequestURI()
|
|
|
|
s.Handler.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
2016-03-27 00:05:17 +00:00
|
|
|
// SetHandler sets handler
|
|
|
|
func (s *StripPrefix) SetHandler(Handler http.Handler) {
|
|
|
|
s.Handler = Handler
|
|
|
|
}
|
2017-11-21 13:28:03 +00:00
|
|
|
|
|
|
|
func stripPrefix(s, prefix string) string {
|
|
|
|
return ensureLeadingSlash(strings.TrimPrefix(s, prefix))
|
|
|
|
}
|
|
|
|
|
|
|
|
func ensureLeadingSlash(str string) string {
|
|
|
|
return "/" + strings.TrimPrefix(str, "/")
|
|
|
|
}
|