-
Notifications
You must be signed in to change notification settings - Fork 5k
/
strip_prefix_regex.go
79 lines (65 loc) · 2.05 KB
/
strip_prefix_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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package stripprefixregex
import (
"context"
"net/http"
"strings"
"github.com/containous/mux"
"github.com/containous/traefik/pkg/config/dynamic"
"github.com/containous/traefik/pkg/middlewares"
"github.com/containous/traefik/pkg/middlewares/stripprefix"
"github.com/containous/traefik/pkg/tracing"
"github.com/opentracing/opentracing-go/ext"
)
const (
typeName = "StripPrefixRegex"
)
// StripPrefixRegex is a middleware used to strip prefix from an URL request.
type stripPrefixRegex struct {
next http.Handler
router *mux.Router
name string
}
// New builds a new StripPrefixRegex middleware.
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefixRegex, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
stripPrefix := stripPrefixRegex{
next: next,
router: mux.NewRouter(),
name: name,
}
for _, prefix := range config.Regex {
stripPrefix.router.PathPrefix(prefix)
}
return &stripPrefix, nil
}
func (s *stripPrefixRegex) GetTracingInformation() (string, ext.SpanKindEnum) {
return s.name, tracing.SpanKindNoneEnum
}
func (s *stripPrefixRegex) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
var match mux.RouteMatch
if s.router.Match(req, &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(req.URL.Path) {
logger := middlewares.GetLogger(req.Context(), s.name, typeName)
logger.Error("Error in stripPrefix middleware", err)
return
}
req.URL.Path = req.URL.Path[len(prefix.Path):]
if req.URL.RawPath != "" {
req.URL.RawPath = req.URL.RawPath[len(prefix.Path):]
}
req.Header.Add(stripprefix.ForwardedPrefixHeader, prefix.Path)
req.RequestURI = ensureLeadingSlash(req.URL.RequestURI())
s.next.ServeHTTP(rw, req)
return
}
http.NotFound(rw, req)
}
func ensureLeadingSlash(str string) string {
return "/" + strings.TrimPrefix(str, "/")
}