traefik/pkg/middlewares/replacepathregex/replace_path_regex.go

76 lines
2.3 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package replacepathregex
import (
"context"
"fmt"
"net/http"
"net/url"
2018-11-14 09:18:03 +00:00
"regexp"
"strings"
"github.com/opentracing/opentracing-go/ext"
"github.com/traefik/traefik/v2/pkg/config/dynamic"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/traefik/traefik/v2/pkg/middlewares"
"github.com/traefik/traefik/v2/pkg/middlewares/replacepath"
"github.com/traefik/traefik/v2/pkg/tracing"
2018-11-14 09:18:03 +00:00
)
const typeName = "ReplacePathRegex"
2018-11-14 09:18:03 +00:00
// ReplacePathRegex is a middleware used to replace the path of a URL request with a regular expression.
type replacePathRegex struct {
next http.Handler
regexp *regexp.Regexp
replacement string
name string
}
// New creates a new replace path regex middleware.
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePathRegex, 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
exp, err := regexp.Compile(strings.TrimSpace(config.Regex))
if err != nil {
2020-05-11 10:06:07 +00:00
return nil, fmt.Errorf("error compiling regular expression %s: %w", config.Regex, err)
2018-11-14 09:18:03 +00:00
}
return &replacePathRegex{
regexp: exp,
replacement: strings.TrimSpace(config.Replacement),
next: next,
name: name,
}, nil
}
func (rp *replacePathRegex) GetTracingInformation() (string, ext.SpanKindEnum) {
return rp.name, tracing.SpanKindNoneEnum
}
func (rp *replacePathRegex) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
currentPath := req.URL.RawPath
if currentPath == "" {
currentPath = req.URL.EscapedPath()
}
if rp.regexp != nil && len(rp.replacement) > 0 && rp.regexp.MatchString(currentPath) {
req.Header.Add(replacepath.ReplacedPathHeader, currentPath)
req.URL.RawPath = rp.regexp.ReplaceAllString(currentPath, rp.replacement)
// as replacement can introduce escaped characters
// Path must remain an unescaped version of RawPath
// Doesn't handle multiple times encoded replacement (`/` => `%2F` => `%252F` => ...)
var err error
req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
if err != nil {
log.FromContext(middlewares.GetLoggerCtx(context.Background(), rp.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()
}
2018-11-14 09:18:03 +00:00
rp.next.ServeHTTP(rw, req)
}