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
|
|
|
|
2023-02-03 14:24:05 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/config/dynamic"
|
|
|
|
"github.com/traefik/traefik/v3/pkg/middlewares"
|
2024-03-12 08:48:04 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
|
2024-01-08 08:10:06 +00:00
|
|
|
"go.opentelemetry.io/otel/trace"
|
2018-11-14 09:18:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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) {
|
2022-11-21 17:36:05 +00:00
|
|
|
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
return &replacePath{
|
|
|
|
next: next,
|
|
|
|
path: config.Path,
|
|
|
|
name: name,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2024-01-08 08:10:06 +00:00
|
|
|
func (r *replacePath) GetTracingInformation() (string, string, trace.SpanKind) {
|
|
|
|
return r.name, typeName, trace.SpanKindInternal
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *replacePath) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
2021-10-08 09:32:08 +00:00
|
|
|
currentPath := req.URL.RawPath
|
|
|
|
if currentPath == "" {
|
|
|
|
currentPath = req.URL.EscapedPath()
|
2020-03-03 15:20:05 +00:00
|
|
|
}
|
|
|
|
|
2021-10-08 09:32:08 +00:00
|
|
|
req.Header.Add(ReplacedPathHeader, currentPath)
|
2020-03-03 15:20:05 +00:00
|
|
|
req.URL.RawPath = r.path
|
|
|
|
|
|
|
|
var err error
|
|
|
|
req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
|
|
|
|
if err != nil {
|
2022-11-21 17:36:05 +00:00
|
|
|
middlewares.GetLogger(context.Background(), r.name, typeName).Error().Err(err).Send()
|
2024-03-12 08:48:04 +00:00
|
|
|
observability.SetStatusErrorf(req.Context(), err.Error())
|
2020-03-03 15:20:05 +00:00
|
|
|
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)
|
|
|
|
}
|