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