2018-11-14 09:18:03 +00:00
|
|
|
package replacepath
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
2020-03-03 15:20:05 +00:00
|
|
|
"net/url"
|
2018-11-14 09:18:03 +00:00
|
|
|
|
2019-08-03 01:58:23 +00:00
|
|
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
2019-09-13 17:28:04 +00:00
|
|
|
"github.com/containous/traefik/v2/pkg/log"
|
2019-08-03 01:58:23 +00:00
|
|
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
|
|
|
"github.com/containous/traefik/v2/pkg/tracing"
|
2018-11-14 09:18:03 +00:00
|
|
|
"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.
|
2019-07-10 07:26:04 +00:00
|
|
|
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePath, name string) (http.Handler, error) {
|
2019-09-13 17:28:04 +00:00
|
|
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
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) {
|
2020-03-03 15:20:05 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
req.RequestURI = req.URL.RequestURI()
|
2019-09-13 17:28:04 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
r.next.ServeHTTP(rw, req)
|
|
|
|
}
|