2018-11-14 09:18:03 +00:00
|
|
|
package addprefix
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/opentracing/opentracing-go/ext"
|
2020-09-16 13:46:04 +00:00
|
|
|
"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/tracing"
|
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.
|
2019-07-10 07:26:04 +00:00
|
|
|
func New(ctx context.Context, next http.Handler, config dynamic.AddPrefix, 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
|
|
|
var result *addPrefix
|
|
|
|
|
|
|
|
if len(config.Prefix) > 0 {
|
|
|
|
result = &addPrefix{
|
|
|
|
prefix: config.Prefix,
|
|
|
|
next: next,
|
|
|
|
name: name,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return nil, fmt.Errorf("prefix cannot be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2019-11-14 09:32:05 +00:00
|
|
|
func (a *addPrefix) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|
|
|
return a.name, tracing.SpanKindNoneEnum
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
2019-11-14 09:32:05 +00:00
|
|
|
func (a *addPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|
|
|
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), a.name, typeName))
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
oldURLPath := req.URL.Path
|
2019-11-14 09:32:05 +00:00
|
|
|
req.URL.Path = ensureLeadingSlash(a.prefix + req.URL.Path)
|
2018-11-14 09:18:03 +00:00
|
|
|
logger.Debugf("URL.Path is now %s (was %s).", req.URL.Path, oldURLPath)
|
|
|
|
|
|
|
|
if req.URL.RawPath != "" {
|
|
|
|
oldURLRawPath := req.URL.RawPath
|
2019-11-14 09:32:05 +00:00
|
|
|
req.URL.RawPath = ensureLeadingSlash(a.prefix + req.URL.RawPath)
|
2018-11-14 09:18:03 +00:00
|
|
|
logger.Debugf("URL.RawPath is now %s (was %s).", req.URL.RawPath, oldURLRawPath)
|
|
|
|
}
|
|
|
|
req.RequestURI = req.URL.RequestURI()
|
|
|
|
|
2019-11-14 09:32:05 +00:00
|
|
|
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
|
|
|
}
|