Documentation
¶
Overview ¶
Package middleware provides composable HTTP middleware for net/http.
Middleware functions wrap http.Handler to add cross-cutting concerns like logging, panic recovery, CORS, security headers, timeouts, compression, and ETag generation. Use Chain to compose multiple middleware together.
Index ¶
- func BearerAuth(validate func(token string) error) func(http.Handler) http.Handler
- func Metrics(onRequest func(method, path string, status int, duration time.Duration)) func(http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequestIDFromContext(ctx context.Context) string
- type CORSOption
- type Middleware
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BearerAuth ¶ added in v0.2.0
BearerAuth validates the Authorization: Bearer <token> header using the provided validate function. If valid, the request is passed downstream. If invalid, responds with 401 Unauthorized.
func Metrics ¶ added in v0.2.0
func Metrics(onRequest func(method, path string, status int, duration time.Duration)) func(http.Handler) http.Handler
Metrics calls onRequest after each request with method, path, status code, and duration.
func RequestID ¶ added in v0.2.0
RequestID generates or propagates an X-Request-ID header. If the incoming request has X-Request-ID, it's preserved. Otherwise a new one is generated.
func RequestIDFromContext ¶ added in v0.2.0
RequestIDFromContext extracts the request ID from the context.
Types ¶
type CORSOption ¶
type CORSOption func(*corsConfig)
CORSOption configures the CORS middleware.
func AllowCredentials ¶
func AllowCredentials() CORSOption
AllowCredentials enables the Access-Control-Allow-Credentials header.
func AllowHeaders ¶
func AllowHeaders(headers ...string) CORSOption
AllowHeaders sets the allowed request headers for CORS requests.
func AllowMethods ¶
func AllowMethods(methods ...string) CORSOption
AllowMethods sets the allowed HTTP methods for CORS requests.
func AllowOrigins ¶
func AllowOrigins(origins ...string) CORSOption
AllowOrigins sets the allowed origins. An empty list or a list containing "*" allows all origins.
func MaxAge ¶
func MaxAge(seconds int) CORSOption
MaxAge sets the maximum time (in seconds) that preflight results can be cached.
type Middleware ¶
Middleware is a function that wraps an http.Handler to add behavior.
func CORS ¶
func CORS(opts ...CORSOption) Middleware
CORS returns middleware that handles Cross-Origin Resource Sharing. By default it allows all origins and the methods GET, POST, HEAD, PUT, DELETE, PATCH.
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain composes multiple middleware into a single Middleware. Middleware are applied in the order given: the first middleware in the list wraps the outermost layer, so it executes first on the way in and last on the way out.
func Compress ¶
func Compress() Middleware
Compress returns middleware that gzip-compresses response bodies when the client indicates support via the Accept-Encoding header. Responses with content types that are already compressed (e.g., images) are skipped.
func ETag ¶
func ETag() Middleware
ETag returns middleware that generates an ETag header based on a SHA-256 hash of the response body. If the request includes an If-None-Match header that matches the computed ETag, a 304 Not Modified response is returned instead.
func Logger ¶
func Logger(logger *slog.Logger) Middleware
Logger returns middleware that logs each request using the provided slog.Logger. It records the HTTP method, path, response status code, and request duration.
func Recover ¶
func Recover() Middleware
Recover returns middleware that recovers from panics in downstream handlers. When a panic occurs, it logs the panic value and stack trace to stderr and responds with a 500 Internal Server Error.
func SecureHeaders ¶
func SecureHeaders() Middleware
SecureHeaders returns middleware that sets common security-related HTTP headers. It sets:
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- Referrer-Policy: strict-origin-when-cross-origin
- X-XSS-Protection: 0
func Timeout ¶
func Timeout(d time.Duration) Middleware
Timeout returns middleware that enforces a timeout on each request. If the handler does not complete within the given duration, the client receives a 503 Service Unavailable response.