-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
replace_path_regex.go
38 lines (33 loc) · 1.07 KB
/
replace_path_regex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package middlewares
import (
"net/http"
"regexp"
"strings"
"github.com/containous/traefik/log"
)
// 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) {
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)
}