forked from traefik/traefik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace_path.go
63 lines (51 loc) · 1.59 KB
/
replace_path.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
package replacepath
import (
"context"
"net/http"
"net/url"
"github.com/cgws/traefik/v2/pkg/config/dynamic"
"github.com/cgws/traefik/v2/pkg/log"
"github.com/cgws/traefik/v2/pkg/middlewares"
"github.com/cgws/traefik/v2/pkg/tracing"
"github.com/opentracing/opentracing-go/ext"
)
const (
// ReplacedPathHeader is the default header to set the old path to.
ReplacedPathHeader = "X-Replaced-Path"
typeName = "ReplacePath"
)
// ReplacePath is a middleware used to replace the path of a URL request.
type replacePath struct {
next http.Handler
path string
name string
}
// New creates a new replace path middleware.
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePath, name string) (http.Handler, error) {
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
return &replacePath{
next: next,
path: config.Path,
name: name,
}, nil
}
func (r *replacePath) GetTracingInformation() (string, ext.SpanKindEnum) {
return r.name, tracing.SpanKindNoneEnum
}
func (r *replacePath) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if req.URL.RawPath == "" {
req.Header.Add(ReplacedPathHeader, req.URL.Path)
} else {
req.Header.Add(ReplacedPathHeader, req.URL.RawPath)
}
req.URL.RawPath = r.path
var err error
req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
if err != nil {
log.FromContext(middlewares.GetLoggerCtx(context.Background(), r.name, typeName)).Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
req.RequestURI = req.URL.RequestURI()
r.next.ServeHTTP(rw, req)
}