traefik/pkg/middlewares/stripprefixregex/strip_prefix_regex.go

87 lines
2 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package stripprefixregex
import (
"context"
"net/http"
2019-09-03 18:32:03 +00:00
"regexp"
2018-11-14 09:18:03 +00:00
"strings"
"github.com/opentracing/opentracing-go/ext"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/stripprefix"
"github.com/traefik/traefik/v3/pkg/tracing"
2018-11-14 09:18:03 +00:00
)
const (
typeName = "StripPrefixRegex"
)
// StripPrefixRegex is a middleware used to strip prefix from an URL request.
type stripPrefixRegex struct {
2019-09-03 18:32:03 +00:00
next http.Handler
expressions []*regexp.Regexp
name string
2018-11-14 09:18:03 +00:00
}
// New builds a new StripPrefixRegex middleware.
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefixRegex, 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
stripPrefix := stripPrefixRegex{
2019-09-03 18:32:03 +00:00
next: next,
name: name,
2018-11-14 09:18:03 +00:00
}
2019-09-03 18:32:03 +00:00
for _, exp := range config.Regex {
reg, err := regexp.Compile(strings.TrimSpace(exp))
if err != nil {
return nil, err
}
stripPrefix.expressions = append(stripPrefix.expressions, reg)
2018-11-14 09:18:03 +00:00
}
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) {
2019-09-03 18:32:03 +00:00
for _, exp := range s.expressions {
parts := exp.FindStringSubmatch(req.URL.Path)
if len(parts) > 0 && len(parts[0]) > 0 {
prefix := parts[0]
if !strings.HasPrefix(req.URL.Path, prefix) {
continue
}
2018-11-14 09:18:03 +00:00
2019-09-03 18:32:03 +00:00
req.Header.Add(stripprefix.ForwardedPrefixHeader, prefix)
2018-11-14 09:18:03 +00:00
req.URL.Path = ensureLeadingSlash(strings.Replace(req.URL.Path, prefix, "", 1))
2019-09-03 18:32:03 +00:00
if req.URL.RawPath != "" {
req.URL.RawPath = ensureLeadingSlash(req.URL.RawPath[len(prefix):])
2019-09-03 18:32:03 +00:00
}
2018-11-14 09:18:03 +00:00
req.RequestURI = req.URL.RequestURI()
2019-09-03 18:32:03 +00:00
s.next.ServeHTTP(rw, req)
return
}
2018-11-14 09:18:03 +00:00
}
2019-09-03 18:32:03 +00:00
s.next.ServeHTTP(rw, req)
2018-11-14 09:18:03 +00:00
}
func ensureLeadingSlash(str string) string {
if str == "" {
return str
}
if str[0] == '/' {
return str
}
return "/" + str
2018-11-14 09:18:03 +00:00
}