traefik/pkg/middlewares/headers/headers.go

70 lines
1.7 KiB
Go
Raw Normal View History

2018-11-14 10:18:03 +01:00
// Package headers Middleware based on https://github.com/unrolled/secure.
package headers
import (
"context"
"errors"
"net/http"
2023-02-03 15:24:05 +01:00
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/connectionheader"
2024-01-08 10:10:06 +02:00
"go.opentelemetry.io/otel/trace"
2018-11-14 10:18:03 +01:00
)
const (
2019-07-12 03:46:04 -06:00
typeName = "Headers"
2018-11-14 10:18:03 +01:00
)
type headers struct {
name string
handler http.Handler
}
// New creates a Headers middleware.
func New(ctx context.Context, next http.Handler, cfg dynamic.Headers, name string) (http.Handler, error) {
2018-11-14 10:18:03 +01:00
// HeaderMiddleware -> SecureMiddleWare -> next
2022-11-21 18:36:05 +01:00
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
hasSecureHeaders := cfg.HasSecureHeadersDefined()
hasCustomHeaders := cfg.HasCustomHeadersDefined()
hasCorsHeaders := cfg.HasCorsHeadersDefined()
2019-04-02 03:40:04 -05:00
if !hasSecureHeaders && !hasCustomHeaders && !hasCorsHeaders {
2018-11-14 10:18:03 +01:00
return nil, errors.New("headers configuration not valid")
}
var handler http.Handler
nextHandler := next
2019-04-02 03:40:04 -05:00
if hasSecureHeaders {
2022-11-21 18:36:05 +01:00
logger.Debug().Msgf("Setting up secureHeaders from %v", cfg)
handler = newSecure(next, cfg, name)
2018-11-14 10:18:03 +01:00
nextHandler = handler
}
2019-04-02 03:40:04 -05:00
if hasCustomHeaders || hasCorsHeaders {
2022-11-21 18:36:05 +01:00
logger.Debug().Msgf("Setting up customHeaders/Cors from %v", cfg)
h, err := NewHeader(nextHandler, cfg)
if err != nil {
return nil, err
}
handler = connectionheader.Remover(h)
2018-11-14 10:18:03 +01:00
}
return &headers{
handler: handler,
name: name,
}, nil
}
2024-01-08 10:10:06 +02:00
func (h *headers) GetTracingInformation() (string, string, trace.SpanKind) {
return h.name, typeName, trace.SpanKindInternal
2018-11-14 10:18:03 +01:00
}
func (h *headers) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
h.handler.ServeHTTP(rw, req)
}