Documentation
¶
Overview ¶
Package middleware provides HTTP middleware components for the listener package.
Index ¶
- Constants
- func CORS(opts ...CORSOption) func(http.Handler) http.Handler
- func Compress() func(http.Handler) http.Handler
- func GetRequestID(ctx context.Context) string
- func Logging() func(http.Handler) http.Handler
- func MaxRequestSize(bytes int64) func(http.Handler) http.Handler
- func RateLimit(requestsPerSecond float64, burst int) func(http.Handler) http.Handler
- func Recovery() func(http.Handler) http.Handler
- func RequestID() func(http.Handler) http.Handler
- func Timeout(duration time.Duration) func(http.Handler) http.Handler
- type CORSOption
- func WithAllowCredentials() CORSOption
- func WithAllowedHeaders(headers ...string) CORSOption
- func WithAllowedMethods(methods ...string) CORSOption
- func WithAllowedOrigins(origins ...string) CORSOption
- func WithExposedHeaders(headers ...string) CORSOption
- func WithMaxAge(seconds int) CORSOption
- func WithOriginValidators(validators ...OriginValidator) CORSOption
- type OriginValidator
Constants ¶
const (
// RequestIDHeader is the HTTP header used for request IDs.
RequestIDHeader = "X-Request-ID"
)
Variables ¶
This section is empty.
Functions ¶
func CORS ¶
func CORS(opts ...CORSOption) func(http.Handler) http.Handler
CORS returns a middleware that handles Cross-Origin Resource Sharing. It processes preflight OPTIONS requests and sets appropriate CORS headers. AllowedOrigins entries are bare hostnames (e.g., "example.com"), and incoming Origin headers are matched by extracting their hostname component. If AllowCredentials is true with only wildcard origins and no explicit origins, credentials are automatically disabled and a warning is logged.
When called with no options, sensible defaults are applied: origins ["*"], methods ["GET","HEAD","POST"], common headers, maxAge 3600.
func Compress ¶
Compress returns a middleware that compresses response bodies using gzip when the client supports it (via Accept-Encoding header). It skips compression for small responses (under 256 bytes) and already-compressed content types.
func GetRequestID ¶
GetRequestID retrieves the request ID from the context.
func Logging ¶
Logging returns a middleware that logs request/response details via global slog. It logs method, path, status code, duration, and request ID (if available). Log level is Info for 2xx/3xx, Warn for 4xx, Error for 5xx.
func MaxRequestSize ¶
MaxRequestSize returns a middleware that limits the size of incoming request bodies using http.MaxBytesReader. Handlers that read the body will receive an error when the limit is exceeded and should respond with 413 Request Entity Too Large.
If bytes is zero or negative, it defaults to 1MB (1048576 bytes) and logs a warning via slog.
func RateLimit ¶
RateLimit returns a middleware that enforces a global rate limit using a token bucket algorithm. When the limit is exceeded, it responds with 429 Too Many Requests and includes a Retry-After header. If requestsPerSecond is not positive, it defaults to 1.0 with a warning log. If burst is not positive, it defaults to 1 with a warning log.
func Recovery ¶
Recovery returns a middleware that recovers from panics in downstream handlers. It logs the panic value and stack trace via global slog.Error and responds with 500 Internal Server Error. If a request ID is available in the context, it is included in the log entry. If the response has already been partially written, it logs an error instead of attempting to write a 500 status.
func RequestID ¶
RequestID is a middleware that assigns a unique snowflake-based request ID to each request. The ID is a 16-character hex string encoding a 64-bit snowflake composed of: 41 bits timestamp (ms since 2026-01-01 UTC), 16 bits machine hash (FNV-1a of hostname), and 7 bits sequence counter. If the X-Request-ID header is already present in the request, it reuses that value. Otherwise, it generates a new snowflake ID. The ID is stored in the request context and set as the X-Request-ID response header.
Types ¶
type CORSOption ¶ added in v0.4.1
type CORSOption func(*corsConfig)
CORSOption configures the CORS middleware.
func WithAllowCredentials ¶ added in v0.4.1
func WithAllowCredentials() CORSOption
WithAllowCredentials enables Access-Control-Allow-Credentials.
func WithAllowedHeaders ¶ added in v0.4.1
func WithAllowedHeaders(headers ...string) CORSOption
WithAllowedHeaders sets the allowed request headers, replacing defaults.
func WithAllowedMethods ¶ added in v0.4.1
func WithAllowedMethods(methods ...string) CORSOption
WithAllowedMethods sets the allowed HTTP methods, replacing defaults.
func WithAllowedOrigins ¶ added in v0.4.1
func WithAllowedOrigins(origins ...string) CORSOption
WithAllowedOrigins sets the allowed origins, replacing defaults. Origins are bare hostnames (e.g., "example.com") or "*" for wildcard.
func WithExposedHeaders ¶ added in v0.4.1
func WithExposedHeaders(headers ...string) CORSOption
WithExposedHeaders sets the headers exposed to the browser.
func WithMaxAge ¶ added in v0.4.1
func WithMaxAge(seconds int) CORSOption
WithMaxAge sets the preflight cache duration in seconds.
func WithOriginValidators ¶ added in v0.4.1
func WithOriginValidators(validators ...OriginValidator) CORSOption
WithOriginValidators sets validators that reject invalid AllowedOrigins entries at construction time.
type OriginValidator ¶ added in v0.4.1
OriginValidator is a function that validates an AllowedOrigins entry. It returns an error if the origin entry is invalid.
func ValidateHostname ¶ added in v0.4.1
func ValidateHostname() []OriginValidator
ValidateHostname returns all hostname validators combined: ValidateNoScheme, ValidateNoPath, ValidateNoPort, ValidateNoWildcard, ValidateNotEmpty.
func ValidateNoPath ¶ added in v0.4.1
func ValidateNoPath() OriginValidator
ValidateNoPath returns a validator that rejects origins containing "/".
func ValidateNoPort ¶ added in v0.4.1
func ValidateNoPort() OriginValidator
ValidateNoPort returns a validator that rejects origins containing a port separator. IPv6 addresses with multiple colons (e.g., "::1") are allowed.
func ValidateNoScheme ¶ added in v0.4.1
func ValidateNoScheme() OriginValidator
ValidateNoScheme returns a validator that rejects origins containing "://".
func ValidateNoWildcard ¶ added in v0.4.1
func ValidateNoWildcard() OriginValidator
ValidateNoWildcard returns a validator that rejects the wildcard origin "*".
func ValidateNotEmpty ¶ added in v0.4.1
func ValidateNotEmpty() OriginValidator
ValidateNotEmpty returns a validator that rejects empty origin strings.