middleware

package
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware components for the listener package.

Index

Constants

View Source
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

func Compress() func(http.Handler) http.Handler

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

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from the context.

func Logging

func Logging() func(http.Handler) http.Handler

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

func MaxRequestSize(bytes int64) func(http.Handler) http.Handler

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

func RateLimit(requestsPerSecond float64, burst int) func(http.Handler) http.Handler

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

func Recovery() func(http.Handler) http.Handler

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

func RequestID() func(http.Handler) http.Handler

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.

func Timeout

func Timeout(duration time.Duration) func(http.Handler) http.Handler

Timeout returns a middleware that enforces a request processing deadline. If the handler does not complete within the given duration, a 503 Service Unavailable response is sent to the client. If duration is not positive, it defaults to 30s with a warning log.

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

type OriginValidator func(origin string) error

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL