2016-02-26 14:29:53 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2017-05-28 03:50:03 +00:00
|
|
|
// ForwardedPrefixHeader is the default header to set prefix
|
|
|
|
const 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-05-22 22:44:02 +00:00
|
|
|
origPrefix := strings.TrimSpace(prefix)
|
|
|
|
if origPrefix == r.URL.Path {
|
|
|
|
r.URL.Path = "/"
|
|
|
|
s.serveRequest(w, r, origPrefix)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
prefix = strings.TrimSuffix(origPrefix, "/") + "/"
|
|
|
|
if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
|
|
|
|
r.URL.Path = "/" + strings.TrimPrefix(p, "/")
|
|
|
|
s.serveRequest(w, r, origPrefix)
|
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
|
|
|
|
2017-05-22 22:44:02 +00:00
|
|
|
func (s *StripPrefix) serveRequest(w http.ResponseWriter, r *http.Request, prefix string) {
|
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
|
|
|
|
}
|