traefik/pkg/middlewares/addprefix/add_prefix.go

74 lines
1.7 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package addprefix
import (
"context"
"errors"
2018-11-14 09:18:03 +00:00
"net/http"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
2024-01-08 08:10:06 +00:00
"go.opentelemetry.io/otel/trace"
2018-11-14 09:18:03 +00:00
)
const (
typeName = "AddPrefix"
)
// AddPrefix is a middleware used to add prefix to an URL request.
type addPrefix struct {
next http.Handler
prefix string
name string
}
// New creates a new handler.
func New(ctx context.Context, next http.Handler, config dynamic.AddPrefix, 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
var result *addPrefix
if len(config.Prefix) > 0 {
result = &addPrefix{
prefix: config.Prefix,
next: next,
name: name,
}
} else {
return nil, errors.New("prefix cannot be empty")
2018-11-14 09:18:03 +00:00
}
return result, nil
}
2024-01-08 08:10:06 +00:00
func (a *addPrefix) GetTracingInformation() (string, string, trace.SpanKind) {
return a.name, typeName, trace.SpanKindInternal
2018-11-14 09:18:03 +00:00
}
func (a *addPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
2022-11-21 17:36:05 +00:00
logger := middlewares.GetLogger(req.Context(), a.name, typeName)
2018-11-14 09:18:03 +00:00
oldURLPath := req.URL.Path
req.URL.Path = ensureLeadingSlash(a.prefix + req.URL.Path)
2022-11-21 17:36:05 +00:00
logger.Debug().Msgf("URL.Path is now %s (was %s).", req.URL.Path, oldURLPath)
2018-11-14 09:18:03 +00:00
if req.URL.RawPath != "" {
oldURLRawPath := req.URL.RawPath
req.URL.RawPath = ensureLeadingSlash(a.prefix + req.URL.RawPath)
2022-11-21 17:36:05 +00:00
logger.Debug().Msgf("URL.RawPath is now %s (was %s).", req.URL.RawPath, oldURLRawPath)
2018-11-14 09:18:03 +00:00
}
req.RequestURI = req.URL.RequestURI()
a.next.ServeHTTP(rw, req)
}
func ensureLeadingSlash(str string) string {
if str == "" {
return str
}
if str[0] == '/' {
return str
}
return "/" + str
2018-11-14 09:18:03 +00:00
}