2017-10-30 11:54:03 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
2018-08-14 16:38:04 +00:00
|
|
|
"context"
|
2017-10-30 11:54:03 +00:00
|
|
|
"net/http"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
"github.com/containous/traefik/old/log"
|
2017-10-30 11:54:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ReplacePathRegex is a middleware used to replace the path of a URL request with a regular expression
|
|
|
|
type ReplacePathRegex struct {
|
|
|
|
Handler http.Handler
|
|
|
|
Regexp *regexp.Regexp
|
|
|
|
Replacement string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewReplacePathRegexHandler returns a new ReplacePathRegex
|
|
|
|
func NewReplacePathRegexHandler(regex string, replacement string, handler http.Handler) http.Handler {
|
|
|
|
exp, err := regexp.Compile(strings.TrimSpace(regex))
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Error compiling regular expression %s: %s", regex, err)
|
|
|
|
}
|
|
|
|
return &ReplacePathRegex{
|
|
|
|
Regexp: exp,
|
|
|
|
Replacement: strings.TrimSpace(replacement),
|
|
|
|
Handler: handler,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *ReplacePathRegex) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if s.Regexp != nil && len(s.Replacement) > 0 && s.Regexp.MatchString(r.URL.Path) {
|
2018-08-14 16:38:04 +00:00
|
|
|
r = r.WithContext(context.WithValue(r.Context(), ReplacePathKey, r.URL.Path))
|
2017-10-30 11:54:03 +00:00
|
|
|
r.Header.Add(ReplacedPathHeader, r.URL.Path)
|
|
|
|
r.URL.Path = s.Regexp.ReplaceAllString(r.URL.Path, s.Replacement)
|
|
|
|
r.RequestURI = r.URL.RequestURI()
|
|
|
|
}
|
|
|
|
s.Handler.ServeHTTP(w, r)
|
|
|
|
}
|