2017-03-24 11:07:59 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
2018-07-31 09:28:03 +00:00
|
|
|
"context"
|
2017-03-24 11:07:59 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/containous/mux"
|
2018-11-14 09:18:03 +00:00
|
|
|
"github.com/containous/traefik/old/log"
|
2017-03-24 11:07:59 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// StripPrefixRegex is a middleware used to strip prefix from an URL request
|
|
|
|
type StripPrefixRegex struct {
|
|
|
|
Handler http.Handler
|
|
|
|
router *mux.Router
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewStripPrefixRegex builds a new StripPrefixRegex given a handler and prefixes
|
|
|
|
func NewStripPrefixRegex(handler http.Handler, prefixes []string) *StripPrefixRegex {
|
|
|
|
stripPrefix := StripPrefixRegex{Handler: handler, router: mux.NewRouter()}
|
|
|
|
|
|
|
|
for _, prefix := range prefixes {
|
|
|
|
stripPrefix.router.PathPrefix(prefix)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &stripPrefix
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StripPrefixRegex) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var match mux.RouteMatch
|
|
|
|
if s.router.Match(r, &match) {
|
|
|
|
params := make([]string, 0, len(match.Vars)*2)
|
|
|
|
for key, val := range match.Vars {
|
|
|
|
params = append(params, key)
|
|
|
|
params = append(params, val)
|
|
|
|
}
|
|
|
|
|
|
|
|
prefix, err := match.Route.URL(params...)
|
|
|
|
if err != nil || len(prefix.Path) > len(r.URL.Path) {
|
|
|
|
log.Error("Error in stripPrefix middleware", err)
|
|
|
|
return
|
|
|
|
}
|
2018-08-14 16:38:04 +00:00
|
|
|
rawReqPath := r.URL.Path
|
2017-03-24 11:07:59 +00:00
|
|
|
r.URL.Path = r.URL.Path[len(prefix.Path):]
|
2017-11-21 13:28:03 +00:00
|
|
|
if r.URL.RawPath != "" {
|
|
|
|
r.URL.RawPath = r.URL.RawPath[len(prefix.Path):]
|
|
|
|
}
|
2018-08-14 16:38:04 +00:00
|
|
|
r = r.WithContext(context.WithValue(r.Context(), StripPrefixKey, rawReqPath))
|
2017-05-28 03:50:03 +00:00
|
|
|
r.Header.Add(ForwardedPrefixHeader, prefix.Path)
|
2018-08-14 16:38:04 +00:00
|
|
|
r.RequestURI = ensureLeadingSlash(r.URL.RequestURI())
|
2017-03-24 11:07:59 +00:00
|
|
|
s.Handler.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
http.NotFound(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetHandler sets handler
|
|
|
|
func (s *StripPrefixRegex) SetHandler(Handler http.Handler) {
|
|
|
|
s.Handler = Handler
|
|
|
|
}
|