Documentation
¶
Overview ¶
Package httputil provides composable HTTP middleware, utility primitives, and server lifecycle helpers for Go.
The library offers CORS configuration, client IP extraction, response recording, middleware chaining, security headers, request ID propagation, panic recovery, request timeout enforcement, structured request logging, response compression, request body decompression with bomb protection, an HTTP server wrapper with graceful shutdown, standard health check handlers (/health, /health/live, /health/ready), W3C Server-Timing instrumentation, CSRF protection (double-submit cookie via justinas/nosurf, with HTMX-aware helpers), and keyed token-bucket rate limiting with min-heap eviction and a MaxKeys cap.
All middleware follows the standard func(http.Handler) http.Handler signature, making it compatible with any Go HTTP framework. Use Chain() to compose multiple middleware — first argument is outermost.
All config types implement Validate() error for startup configuration checks.
Errors from ResponseRecorder operations are classified using go-error-family with behavioral families (Transient, Infrastructure) for retry decisions and structured observability. RegisterErrorClassifications also registers the go-etag error-code classifications once per process — the go-etag dependency is for that error-code registration; conditional-request (ETag) handling itself lives in the separate github.com/larsartmann/go-etag module.
Example (ConditionalRequests) ¶
helloHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("hello world"))
})
handler := etag.New(etag.DefaultETagConfig())(helloHandler)
// First request: the middleware computes and sets the ETag header.
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
generated := rec.Header().Get("ETag")
fmt.Println(generated != "")
// Second request with matching If-None-Match: 304 Not Modified, empty body.
rec2 := httptest.NewRecorder()
req2 := httptest.NewRequest(http.MethodGet, "/", nil)
req2.Header.Set("If-None-Match", generated)
handler.ServeHTTP(rec2, req2)
fmt.Println(rec2.Code)
Output: true 304
Index ¶
- Constants
- Variables
- func CSRFMiddleware(cfg CSRFConfig) func(http.Handler) http.Handler
- func CSRFResponseHeaderMiddleware(next http.Handler) http.Handler
- func CSRFTestToken(middleware func(http.Handler) http.Handler) (string, *http.Cookie)
- func CSRFTokenFormField(r *http.Request) string
- func CSRFTokenFromContext(ctx context.Context) string
- func CSRFTokenFromRequest(r *http.Request) string
- func CSRFTokenHTMLMeta(r *http.Request) string
- func CSRFTokenHXHeaders(r *http.Request) string
- func Chain(handler http.Handler, middlewares ...Middleware) http.Handler
- func ClientIP(req *http.Request) string
- func ClientIPFromContext(ctx context.Context) string
- func ClientIPMiddleware(next http.Handler) http.Handler
- func ConfigureNosurfHandler(handler *nosurf.CSRFHandler, cfg CSRFConfig)
- func DefaultIncompressibleTypes() []string
- func DefaultWriterFactories() map[string]WriterFactory
- func DefaultWriterFactoriesForLevel(level int) map[string]WriterFactory
- func ForbiddenHandler(w http.ResponseWriter, _ *http.Request, _ error)
- func HealthHandler() http.HandlerFunc
- func InDomain(err error, domain Domain) bool
- func InvalidateCSRFCookie(w http.ResponseWriter, cfg CSRFConfig)
- func KeyedRateLimiterMiddleware(cfg KeyedRateLimiterConfig) func(http.Handler) http.Handler
- func LanguageFromContext(ctx context.Context) string
- func LanguageFromRequest(r *http.Request) string
- func LiveHandler() http.HandlerFunc
- func NonceAttr(r *http.Request) string
- func NonceFromContext(ctx context.Context) string
- func NonceFromRequest(r *http.Request) string
- func ParseUintQuery(r *http.Request, key string) uint
- func ProductionCSPWithNonce(nonce string) string
- func ReadyHandler() http.HandlerFunc
- func ReadyHandlerWithProbe(ready func() bool) http.HandlerFunc
- func RecommendedCSPWithNonce(nonce string) string
- func RegisterErrorClassifications()
- func RegisterHealth(mux *http.ServeMux)
- func RequestIDFromContext(ctx context.Context) string
- func SetPlaintextHTTPOrigin(r *http.Request, cfg CSRFConfig)
- func TranslateCSRFHeaders(r *http.Request, cfg CSRFConfig)
- func ValidateCSRF(r *http.Request, cfg CSRFConfig) (bool, *httptest.ResponseRecorder)
- func WithCSRFToken(ctx context.Context, token string) context.Context
- func WithClientIP(parent context.Context, ip string) context.Context
- func WithLanguage(parent context.Context, tag string) context.Context
- func WithNonce(parent context.Context, nonce string) context.Context
- type AbsentEncodingPolicy
- type CORSConfig
- type CSRFConfig
- type Capabilities
- type Code
- func (c Code) Conflict(message string) *errorfamily.Error
- func (c Code) Corruption(message string) *errorfamily.Error
- func (c Code) Domain() Domain
- func (c Code) Infrastructure(message string) *errorfamily.Error
- func (c Code) Orchestration(message string) *errorfamily.Error
- func (c Code) Rejection(message string) *errorfamily.Error
- func (c Code) Transient(message string) *errorfamily.Error
- func (c Code) WrapConflict(cause error, message string) *errorfamily.Error
- func (c Code) WrapCorruption(cause error, message string) *errorfamily.Error
- func (c Code) WrapInfrastructure(cause error, message string) *errorfamily.Error
- func (c Code) WrapOrchestration(cause error, message string) *errorfamily.Error
- func (c Code) WrapRejection(cause error, message string) *errorfamily.Error
- func (c Code) WrapTransient(cause error, message string) *errorfamily.Error
- type CompressionConfig
- type DecompressionConfig
- type Domain
- type ErrorHandler
- type HealthResponse
- type HealthStatus
- type KeyExtractor
- type KeyedRateLimiter
- type KeyedRateLimiterConfig
- type LanguageConfig
- type LanguageExtractor
- func LanguageExtractorChain(extractors ...LanguageExtractor) LanguageExtractor
- func LanguageExtractorFromAcceptHeader() LanguageExtractor
- func LanguageExtractorFromCookie(name string) LanguageExtractor
- func LanguageExtractorFromPathPrefix(prefixes map[string]string) LanguageExtractor
- func LanguageExtractorFromQuery(param string) LanguageExtractor
- type MaxBodySizeConfig
- type MetricsConfig
- type MetricsRecorder
- type Middleware
- func CORS(cfg CORSConfig) Middleware
- func Compose(middlewares ...Middleware) Middleware
- func Compression(cfg CompressionConfig) Middleware
- func Decompression(cfg DecompressionConfig) Middleware
- func Language(cfg LanguageConfig) Middleware
- func Logging(logger *slog.Logger) Middleware
- func LoggingFromContext(fallback *slog.Logger, fromContext func(context.Context) *slog.Logger) Middleware
- func MaxBodySize(maxBytes int64) Middleware
- func MaxBodySizeMiddleware(cfg MaxBodySizeConfig) Middleware
- func Metrics(cfg MetricsConfig) Middleware
- func Nonce(cfg NonceConfig) Middleware
- func Recovery(logger *slog.Logger) Middleware
- func RecoveryWithConfig(cfg RecoveryConfig) Middleware
- func RequestID(cfg RequestIDConfig) Middleware
- func SecurityHeaders(cfg SecurityHeadersConfig) Middleware
- func Timeout(duration time.Duration) Middleware
- type MiddlewareFunc
- type MiddlewareStack
- type NonceConfig
- type RecoveryConfig
- type RequestIDConfig
- type ResponseRecorder
- func (r *ResponseRecorder) Flush()
- func (r *ResponseRecorder) HeaderSnapshot() http.Header
- func (r *ResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *ResponseRecorder) Push(target string, opts *http.PushOptions) error
- func (r *ResponseRecorder) Status() int
- func (r *ResponseRecorder) Write(b []byte) (int, error)
- func (r *ResponseRecorder) WriteHeader(code int)
- func (r *ResponseRecorder) WroteHeader() bool
- type SecurityHeadersConfig
- type Server
- type ServerConfig
- type TagMatcher
- type TrustedProxySet
- type WriterFactory
Examples ¶
- Package (ConditionalRequests)
- CORS
- CORS (PrivateNetwork)
- CSRFConfig (SameSiteFallback)
- CSRFMiddleware
- CSRFTokenFormField
- CSRFTokenHXHeaders
- Chain
- Chain (Composition)
- Chain (NonceSecurityHeaders)
- ClientIP
- ClientIP (Trust)
- Compose
- Compose (Ordered)
- Compression
- Compression (AbsentEncoding)
- Decompression
- Decompression (MaxSize)
- DomainOf
- HealthHandler
- InDomain
- InDomain (RetryDecision)
- KeyedRateLimiter (EvictionTTL)
- KeyedRateLimiterMiddleware
- KeyedRateLimiterMiddleware (MaxKeys)
- Language
- Logging
- MaxBodySize
- Metrics
- MiddlewareFunc.Then
- MiddlewareStack
- NewKeyedRateLimiter
- NewResponseRecorder
- NewResponseRecorder (Unwritten)
- NewServerListener
- Nonce
- ParseUintQuery
- ReadyHandlerWithProbe
- Recovery
- RecoveryWithConfig
- RequestID
- SecurityHeaders
- Server
- Timeout
Constants ¶
const ( // DefaultCSRFCookieName is the default name of the CSRF cookie. DefaultCSRFCookieName = "csrf_token" // DefaultCSRFHeaderName is the default request header containing the CSRF // token. HTMX sends this header when configured with hx-headers. The value // uses Go's canonical MIME header form; HTTP header names are // case-insensitive, so this matches the conventional X-CSRF-Token spelling. DefaultCSRFHeaderName = "X-Csrf-Token" // DefaultCSRFFieldName is the default form field name for the CSRF token. DefaultCSRFFieldName = "csrf_token" )
const ( // ErrCodeWriteFailed is returned when the underlying ResponseWriter.Write fails. // Classified as Transient (retryable). ErrCodeWriteFailed = "http.write_failed" // ErrCodeHijackUnsupported is returned when the underlying ResponseWriter // does not implement http.Hijacker. Classified as Infrastructure (not retryable). ErrCodeHijackUnsupported = "http.hijack_unsupported" // ErrCodeHijackFailed is returned when the underlying Hijack call fails. // Classified as Transient (retryable): the failure usually means the client // connection dropped or the writer was already hijacked, and a fresh request // may succeed. ErrCodeHijackFailed = "http.hijack_failed" // ErrCodePushUnsupported is returned when the underlying ResponseWriter // does not implement http.Pusher. Classified as Infrastructure (not retryable). ErrCodePushUnsupported = "http.push_unsupported" // ErrCodePushFailed is returned when the underlying Push call fails. // Classified as Transient (retryable): HTTP/2 server push failures are // usually stream-level (the stream was reset or the connection is going // away), and pushing on a fresh request may succeed. ErrCodePushFailed = "http.push_failed" // ErrCodeCompressWriteFailed is returned when gzip write during // compression fails. Classified as Transient (retryable). ErrCodeCompressWriteFailed = "http.compress_write_failed" )
Error codes for classified errors returned by ResponseRecorder operations. All codes use the http. namespace and are compatible with go-error-family for family classification (Rejection, Transient, Infrastructure, Corruption) and retry decisions.
const ( DefaultRateLimit = 100 DefaultRateWindow = time.Minute DefaultRateTTL = 10 * time.Minute )
Keyed rate limiter defaults.
const ( // SecurityHeaderSkip is the sentinel value for suppressing a default // security header. Set ContentTypeOptions, FrameOptions, or // ReferrerPolicy to this value to omit that header entirely: // // httputil.SecurityHeadersConfig{ // ContentTypeOptions: httputil.SecurityHeaderSkip, // ContentSecurityPolicy: httputil.RecommendedCSP, // } SecurityHeaderSkip = "-" // RecommendedHSTS is a recommended Strict-Transport-Security value for production. RecommendedHSTS = "max-age=31536000; includeSubDomains" // RecommendedCSP is a baseline Content-Security-Policy for HTMX applications. // Allows scripts from self (required for HTMX) and styles from self. RecommendedCSP = "default-src 'self'; script-src 'self'; style-src 'self'" )
Frame options values for SecurityHeadersConfig.FrameOptions. Per RFC 7034 §2.1, valid values are DENY, SAMEORIGIN, or absent (the header is omitted entirely).
const ( MiddlewareRecovery = "recovery" MiddlewareLogging = "logging" MiddlewareRequestID = "request-id" MiddlewareCORS = "cors" MiddlewareSecurityHeaders = "security-headers" MiddlewareCompression = "compression" MiddlewareDecompression = "decompression" MiddlewareTimeout = "timeout" MiddlewareClientIP = "client-ip" MiddlewareCSRF = "csrf" MiddlewareServerTiming = "server-timing" MiddlewareKeyedRateLimit = "keyed-rate-limit" MiddlewareETag = "etag" MiddlewareNonce = "nonce" MiddlewareLanguage = "language" )
Well-known middleware names for use with MiddlewareStack. Use these when calling MiddlewareStack.Add to enable ordering validation.
Variables ¶
var ErrCSRFAttestationConflict = errorfamily.NewRejection( string(codeCSRFAttestationConflict), "Sec-Fetch-Site attestation contradicts the Origin header", )
ErrCSRFAttestationConflict is returned when a client-supplied "Sec-Fetch-Site: same-origin" attestation is contradicted by an Origin header from a different, untrusted origin. Browsers never produce this combination — they attest cross-origin requests as cross-site — so a contradiction means the attestation was forged.
var ErrCSRFConfig = errorfamily.NewInfrastructure( string(codeCSRFConfig), "invalid CSRF configuration", )
ErrCSRFConfig is returned when the CSRF configuration is invalid or insecure.
var ErrCSRFInvalid = errorfamily.NewRejection( string(codeCSRFInvalid), "invalid or missing CSRF token", )
ErrCSRFInvalid is returned when a CSRF token is missing, malformed, or does not match. Uses justinas/nosurf under the hood for token generation and validation.
Functions ¶
func CSRFMiddleware ¶
func CSRFMiddleware(cfg CSRFConfig) func(http.Handler) http.Handler
CSRFMiddleware returns HTTP middleware that implements double-submit cookie CSRF protection with HTMX awareness.
Uses justinas/nosurf internally for:
- Cryptographically secure token generation (crypto/rand)
- Per-request token masking (BREACH attack mitigation)
- Same-origin validation via Origin/Referer/Sec-Fetch-Site headers
- Trusted origins support for cross-domain use cases
For GET/HEAD/OPTIONS/TRACE requests, the middleware ensures a CSRF token cookie exists and stores the masked token in context for use in templates. HTTP QUERY (RFC 10008) is treated the same way: it is spec-safe and idempotent like GET, so it passes without a token (QUERY used to be challenged like a mutation before that safe-list alignment).
For state-changing methods (POST/PUT/PATCH/DELETE), it validates that the request includes a matching token in either:
- The X-Csrf-Token header (HTMX default)
- A form field named "csrf_token"
Origin attestation trust model ¶
nosurf (verified at v1.2.0) skips Origin/Referer validation entirely when a request carries a literal "Sec-Fetch-Site: same-origin" header. Browsers set Sec-Fetch-Site truthfully and JavaScript cannot forge it (forbidden header name), so the attestation is reliable against the classic cross-site attacker; any non-browser client, however, can send it manually. Two deliberate consequences:
- A client-supplied attestation (or the plaintext-proxy bypass) skips only the origin check — the masked-token check still gates every state-changing request. This is what lets non-browser API clients, which cannot pass Origin/Referer validation, work with valid tokens.
- A client-supplied attestation contradicted by an Origin header from a different, untrusted origin is rejected with ErrCSRFAttestationConflict before nosurf sees the request: browsers never produce that combination, so it can only be forged.
SameSite=None fallback ¶
A SameSite=None cookie without Secure is refused by current browsers (rfc6265bis §5.7), which would break every state-changing browser request. The constructor therefore falls back to Secure=true for that combination and logs the change; AllowInsecureSameSiteNone keeps the insecure cookie for legacy-client deployments. Validate reports the combination either way.
Known limitation (pattern propagation): this middleware delegates to justinas/nosurf, which forks the request INTERNALLY (addNosurfContext → r.WithContext) and does not copy the matched ServeMux pattern back onto the caller's request. Route readers OUTSIDE the CSRF middleware (otelhttp, metrics aggregating on r.Pattern) see an empty Pattern for CSRF-wrapped routes. Fixing it requires nosurf-side propagation — not possible from this package without wrapping nosurf's internals. CSRF is not in any default middleware stack, so the default appkit wiring is unaffected (verified 2026-09-16; context: LarsArtmann/go-appkit otel pattern work).
Example ¶
handler := CSRFMiddleware(
CSRFConfig{},
)(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}),
)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "127.0.0.1:1234"
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
Output: 200
func CSRFResponseHeaderMiddleware ¶
CSRFResponseHeaderMiddleware returns HTTP middleware that automatically sets the X-Csrf-Token response header on every request. This eliminates the need for individual handlers to manually set the token. The middleware only ever writes a response header; it cannot emit cookies (the token must come from a wrapping CSRFMiddleware).
Place this AFTER CSRFMiddleware in the chain so the token is already in context.
func CSRFTestToken ¶
CSRFTestToken extracts a valid CSRF token AND cookie by making a GET request through the given middleware chain. The middleware must include CSRFMiddleware. CSRFResponseHeaderMiddleware is optional — without it, the token is extracted from the request context instead of the response header.
nosurf uses token masking: the cookie value is NOT the same as the valid header token. A masked token is derived from the cookie per-request. This helper handles that dance automatically, returning both the masked token and the cookie that nosurf set.
func CSRFTokenFormField ¶
CSRFTokenFormField returns a hidden input HTML element containing the CSRF token.
Example ¶
handler := CSRFMiddleware(
CSRFConfig{},
)(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<form method="post">`+CSRFTokenFormField(r)+`</form>`)
}),
)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
body := rec.Body.String()
fmt.Println(
strings.HasPrefix(
body,
`<form method="post"><input type="hidden" name="csrf_token" value="`,
),
)
fmt.Println(strings.HasSuffix(body, `"></form>`))
Output: true true
func CSRFTokenFromContext ¶
CSRFTokenFromContext retrieves the CSRF token stored by CSRFMiddleware. Returns an empty string if no token is present.
func CSRFTokenFromRequest ¶
CSRFTokenFromRequest extracts the CSRF token from either the nosurf request context or the httputil context. Returns "" if no token is present.
func CSRFTokenHTMLMeta ¶
CSRFTokenHTMLMeta returns an HTML meta tag containing the CSRF token.
func CSRFTokenHXHeaders ¶
CSRFTokenHXHeaders returns an HTMX hx-headers attribute with the CSRF token.
Example ¶
handler := CSRFMiddleware(
CSRFConfig{},
)(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<body "+CSRFTokenHXHeaders(r)+">")
}),
)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(strings.HasPrefix(rec.Body.String(), `<body hx-headers='`))
Output: true
func Chain ¶
func Chain(handler http.Handler, middlewares ...Middleware) http.Handler
Chain wraps a handler with multiple middleware, applying them in reverse order so the first middleware in the variadic list is the outermost.
Example ¶
wrapper := func(name string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Order", name)
next.ServeHTTP(w, r)
})
}
}
handler := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})
chain := Chain(handler, wrapper("first"), wrapper("second"))
rec := httptest.NewRecorder()
chain.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(rec.Header().Values("X-Order"))
Output: [first second]
Example (Composition) ¶
mux := http.NewServeMux()
mux.HandleFunc("/api", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "ok")
})
// Chain applies middlewares in declaration order (first = outermost), so
// Recovery outermost catches panics from everything inside it.
handler := Chain(
mux,
Recovery(slog.New(slog.DiscardHandler)),
RequestID(DefaultRequestIDConfig()),
CORS(DefaultCORSConfig()),
)
req := httptest.NewRequest(http.MethodGet, "/api", nil)
req.Header.Set("Origin", "https://example.com")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
fmt.Println(rec.Body.String() == "ok\n")
fmt.Println(rec.Header().Get("X-Request-ID") != "")
fmt.Println(rec.Header().Get("Access-Control-Allow-Origin"))
Output: 200 true true *
Example (NonceSecurityHeaders) ¶
const staticCSP = "default-src 'self'"
staticCfg := DefaultSecurityHeadersConfig()
staticCfg.ContentSecurityPolicy = staticCSP
nonceCfg := DefaultNonceConfig()
nonceCfg.CSPBuilder = RecommendedCSPWithNonce
// Nonce inner to SecurityHeaders: both write Content-Security-Policy on
// the request path, so the nonce-bearing policy overwrites the static one.
handler := Chain(
http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}),
SecurityHeaders(staticCfg),
Nonce(nonceCfg),
)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
csp := rec.Header().Get("Content-Security-Policy")
fmt.Println(strings.Contains(csp, "'nonce-"))
fmt.Println(csp == staticCSP)
Output: true false
func ClientIP ¶
ClientIP extracts the client IP address from the request using the following precedence: X-Forwarded-For (first entry), X-Real-IP, then RemoteAddr with net.SplitHostPort.
Warning: trusts X-Forwarded-For and X-Real-IP headers without validation. Only use behind a reverse proxy that strips/overwrites these headers.
Example ¶
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Forwarded-For", "203.0.113.1, 70.41.3.18")
req.RemoteAddr = "10.0.0.1:1234"
fmt.Println(ClientIP(req))
Output: 203.0.113.1
Example (Trust) ¶
// ClientIP reads X-Forwarded-For blindly. Here the header is
// attacker-set and the real peer is 203.0.113.7; only trust the header
// behind a reverse proxy that strips or overwrites it.
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Forwarded-For", "9.9.9.9")
req.RemoteAddr = "203.0.113.7:4444"
fmt.Println(ClientIP(req))
Output: 9.9.9.9
func ClientIPFromContext ¶
ClientIPFromContext retrieves a previously stored client IP from the context. Returns empty string if no IP was stored.
func ClientIPMiddleware ¶
ClientIPMiddleware extracts the client IP and stores it in the request context for downstream handlers.
func ConfigureNosurfHandler ¶
func ConfigureNosurfHandler(handler *nosurf.CSRFHandler, cfg CSRFConfig)
ConfigureNosurfHandler applies CSRFConfig settings to a nosurf handler. The configuration is applied verbatim, with no fallback: unlike CSRFMiddleware, a SameSite=None + Secure=false combination is passed through as-is, which current browsers refuse to store (rfc6265bis §5.7). Reproduce the Secure fallback CSRFMiddleware performs before calling this if you need the hardened behavior.
The QUERY safe-listing is likewise a CSRFMiddleware behavior only: nosurf v1.2.0's own safe-method list does not know RFC 10008's QUERY, so a handler configured through this low-level function challenges token-less QUERY requests. Register your own ExemptFunc if you build the handler this way and want QUERY treated as spec-safe.
func DefaultIncompressibleTypes ¶
func DefaultIncompressibleTypes() []string
DefaultIncompressibleTypes returns the default list of content-type prefixes that should not be compressed (images, video, audio, pre-compressed archives). Use this to extend rather than replace the defaults in CompressionConfig.IncompressibleTypes.
func DefaultWriterFactories ¶
func DefaultWriterFactories() map[string]WriterFactory
DefaultWriterFactories returns a fresh map containing the stdlib encodings (gzip, deflate, identity) at gzip.DefaultCompression. Useful when extending WriterFactories without dropping the built-ins.
func DefaultWriterFactoriesForLevel ¶
func DefaultWriterFactoriesForLevel(level int) map[string]WriterFactory
DefaultWriterFactoriesForLevel returns a fresh map containing the stdlib encodings (gzip, deflate, identity) at the given compression level. Use this when you want CompressionConfig.Level to take effect without supplying a custom WriterFactories map.
Unlike CompressionConfig.Level, the level parameter follows compress/gzip semantics literally: 0 means gzip.NoCompression here, not "unset". Pass gzip.DefaultCompression (-1) for the default level.
func ForbiddenHandler ¶
func ForbiddenHandler(w http.ResponseWriter, _ *http.Request, _ error)
ForbiddenHandler responds with HTTP 403 Forbidden and no body. Useful for tests and consumers who want to handle CSRF failures via a separate middleware rather than rendering the underlying nosurf error.
func HealthHandler ¶
func HealthHandler() http.HandlerFunc
HealthHandler returns an http.HandlerFunc that responds with a simple {"status": "up"} JSON payload. Use this for basic liveness probes.
The trailing newline after the JSON body (producing `{"status":"up"}\n`, 16 bytes) is intentional: the newline improves terminal output and matches the convention of json.Marshal followed by fmt.Println. The exact-byte test in health_test.go guards this behavior.
Example ¶
rec := httptest.NewRecorder()
HealthHandler()(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
fmt.Println(rec.Code)
fmt.Println(rec.Header().Get("Content-Type"))
fmt.Print(rec.Body.String())
Output: 200 application/json {"status":"up"}
func InDomain ¶
InDomain reports whether err carries an error code in the given domain. Use it to route errors by failing component without string parsing:
if httputil.InDomain(err, httputil.Domain("cors")) { ... }
Example ¶
cfg := DefaultCORSConfig()
cfg.MaxAge = -1
err := cfg.Validate()
if err != nil && InDomain(err, Domain("cors")) {
fmt.Println("fix the CORS configuration, then retry")
}
Output: fix the CORS configuration, then retry
Example (RetryDecision) ¶
cfg := DefaultCORSConfig() cfg.MaxAge = -1 err := cfg.Validate() domain, ok := DomainOf(err) fmt.Println(ok, domain) // Rejection-family errors are never retryable: retrying the same input // cannot succeed, so fix the configuration instead. fmt.Println(errorfamily.Classify(err).IsRetryable())
Output: true cors false
func InvalidateCSRFCookie ¶
func InvalidateCSRFCookie(w http.ResponseWriter, cfg CSRFConfig)
InvalidateCSRFCookie invalidates the current CSRF cookie, forcing a new token to be generated on the next request. Call this on login/logout to prevent CSRF fixation attacks. The deletion cookie matches the middleware's cookie, including the SameSite=None fallback to Secure=true.
func KeyedRateLimiterMiddleware ¶
func KeyedRateLimiterMiddleware(cfg KeyedRateLimiterConfig) func(http.Handler) http.Handler
KeyedRateLimiterMiddleware returns HTTP middleware that rate-limits requests using a token bucket per key.
If the rate limit is exceeded the middleware responds with 429 Too Many Requests and a Retry-After header in seconds. The default value is the configured Window in whole seconds (truncated); custom RejectionHandler and OnRejected callbacks receive the same string.
Tokens are consumed at admission: the decision is instantaneous and request cancellation does not refund the consumed budget.
The internal per-key limiter map uses min-heap-based eviction (default 10 min TTL). For monitoring, use NewKeyedRateLimiter instead.
Example ¶
cfg := KeyedRateLimiterConfig{
Limit: 100,
Window: time.Minute,
KeyExtractor: KeyExtractorFromRemoteAddr(),
}
handler := KeyedRateLimiterMiddleware(
cfg,
)(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}),
)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "1.2.3.4:1234"
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
Output: 200
Example (MaxKeys) ¶
cfg := KeyedRateLimiterConfig{
Limit: 1,
Window: time.Minute,
KeyExtractor: KeyExtractorFromRemoteAddr(),
MaxKeys: 1,
}
handler := KeyedRateLimiterMiddleware(
cfg,
)(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}),
)
request := func(remoteAddr string) int {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = remoteAddr
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec.Code
}
fmt.Println(request("10.0.0.1:1000"))
fmt.Println(request("10.0.0.1:1000"))
fmt.Println(request("10.0.0.2:1000"))
fmt.Println(request("10.0.0.1:1000"))
Output: 200 429 200 200
func LanguageFromContext ¶ added in v1.6.0
LanguageFromContext retrieves the negotiated language tag. Returns an empty string when no language was stored.
func LanguageFromRequest ¶ added in v1.6.0
LanguageFromRequest retrieves the negotiated language tag from the request context. Returns an empty string when no language was stored.
func LiveHandler ¶
func LiveHandler() http.HandlerFunc
LiveHandler returns an http.HandlerFunc for Kubernetes liveness probes. It is functionally equivalent to HealthHandler but semantically distinct.
func NonceAttr ¶
NonceAttr returns an HTML nonce attribute (e.g. `nonce="abc123"`) suitable for use in <script> and <style> tags within Go templates:
<script {{ NonceAttr }}>...</script>
<style {{ NonceAttr }}>...</style>
Returns an empty string when no nonce is present, so templates render `<script >...</script>` (harmless) instead of `<script nonce="">` (invalid). The nonce value is HTML-escaped for defense in depth, though base64 URL-safe encoding only produces [A-Za-z0-9_-] which requires no escaping.
func NonceFromContext ¶
NonceFromContext retrieves the nonce from the context. Returns an empty string if no nonce was stored.
func NonceFromRequest ¶
NonceFromRequest retrieves the nonce from the request context. Returns an empty string if no nonce was stored. Convenience wrapper around NonceFromContext.
func ParseUintQuery ¶
ParseUintQuery extracts a base-10 unsigned integer from the named query parameter in the request URL. It returns 0 if the parameter is missing, empty, or not a valid unsigned integer within the 32-bit range.
Callers that need clamped defaults (e.g. pagination) should pass the result through a constructor that applies sensible defaults for zero values.
Example ¶
req := httptest.NewRequest(http.MethodGet, "/?page=3&limit=20", nil)
page := ParseUintQuery(req, "page")
fmt.Println("page:", page)
Output: page: 3
func ProductionCSPWithNonce ¶
ProductionCSPWithNonce returns a stricter Content-Security-Policy for production deployments: adds object-src 'none' (blocks Flash/plugins), base-uri 'self' (prevents base-tag hijacking), and frame-ancestors 'none' (clickjacking defense via CSP instead of X-Frame-Options). Use this as NonceConfig.CSPBuilder when you want defense-in-depth beyond the baseline RecommendedCSPWithNonce.
func ReadyHandler ¶
func ReadyHandler() http.HandlerFunc
ReadyHandler returns an http.HandlerFunc for Kubernetes readiness probes. The default implementation always reports up. To supply a readiness check that verifies dependencies (database, cache, etc.), use ReadyHandlerWithProbe.
func ReadyHandlerWithProbe ¶
func ReadyHandlerWithProbe(ready func() bool) http.HandlerFunc
ReadyHandlerWithProbe returns an http.HandlerFunc that calls the provided readiness function on each request. When ready returns true, the handler responds with 200 {"status":"up"}. When it returns false, the handler responds with 503 {"status":"down"}. This lets Kubernetes route traffic away from instances that are alive but not yet ready to serve (e.g., still warming caches or waiting on dependencies).
Example ¶
handler := ReadyHandlerWithProbe(func() bool { return true })
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/health/ready", nil)
handler.ServeHTTP(rec, req)
fmt.Print(rec.Body.String())
Output: {"status":"up"}
func RecommendedCSPWithNonce ¶
RecommendedCSPWithNonce returns a Content-Security-Policy header value that extends RecommendedCSP with per-request nonces for script-src and style-src. Use this as NonceConfig.CSPBuilder, or call it directly if you prefer to set the CSP header yourself.
func RegisterErrorClassifications ¶
func RegisterErrorClassifications()
RegisterErrorClassifications maps stdlib HTTP sentinel errors to their behavioral families and registers error message templates for all httputil and go-etag error codes. Call once during program startup to enable classification of HTTP errors via errorfamily.Classify.
This registers a strict superset of go-etag's error templates and stdlib classifications, so consumers need only call this once. Do not also call etag.RegisterErrorClassifications.
Deliberately NOT guarded by sync.Once: the underlying registry merges classifications (map overwrite under a lock), so repeat calls are harmless idempotent re-registrations and the call-once guidance is about intent, not safety.
func RegisterHealth ¶
RegisterHealth registers /health, /health/live, and /health/ready on the given *http.ServeMux using the default handlers.
func RequestIDFromContext ¶
RequestIDFromContext retrieves the request ID from the context. Returns empty string if no ID was stored.
func SetPlaintextHTTPOrigin ¶
func SetPlaintextHTTPOrigin(r *http.Request, cfg CSRFConfig)
SetPlaintextHTTPOrigin sets the Sec-Fetch-Site header to "same-origin" for plain HTTP requests without origin headers. This allows nosurf to skip origin validation for HTTP deployments behind trusted proxies.
It only fills a blank: requests that already carry Sec-Fetch-Site, Origin, or Referer pass through untouched. The forged value is exactly what a non-browser client could send itself — nosurf v1.2.0 short-circuits origin validation on any literal same-origin attestation — so the bypass grants no client new power; the masked-token check still applies.
func TranslateCSRFHeaders ¶
func TranslateCSRFHeaders(r *http.Request, cfg CSRFConfig)
TranslateCSRFHeaders maps custom header/field names to nosurf's default header name. nosurf hardcodes its header and field names, so we translate before passing the request to nosurf.
func ValidateCSRF ¶
func ValidateCSRF(r *http.Request, cfg CSRFConfig) (bool, *httptest.ResponseRecorder)
ValidateCSRF checks whether a request passes CSRF validation against the given config. Returns (true, nil) when valid, or (false, rec) when the request fails validation — the recorder contains the failure response (headers, status code, body) that should be copied to the real ResponseWriter.
Caller-request mutation ¶
ValidateCSRF mutates r in place, mirroring exactly what CSRFMiddleware does to a request before the nosurf handler runs:
- SetPlaintextHTTPOrigin may set "Sec-Fetch-Site: same-origin" on a plain-HTTP request that carries no origin headers (the trusted-proxy plaintext bypass).
- TranslateCSRFHeaders may set the X-Csrf-Token header from the configured custom header or form field. Reading a custom form field calls r.PostFormValue, which parses and caches the request form.
- nosurf itself never leaks into the caller's request: it validates a context-annotated copy, so its token and failure reason stay internal.
"Already validated" is inferred, not tracked: the (true, nil) short-circuit fires when r already carries a nosurf token, which only happens when CSRFMiddleware ran upstream on the same request. There is no validation-marker context flag — a second ValidateCSRF call on the same unvalidated request re-runs the full validation (and is idempotent).
func WithCSRFToken ¶
WithCSRFToken stores a CSRF token in the context.
func WithClientIP ¶
WithClientIP stores the extracted client IP in the request context. Retrieve it later with ClientIPFromContext.
func WithLanguage ¶ added in v1.6.0
WithLanguage stores the negotiated language tag in the context. Retrieve it with LanguageFromContext or LanguageFromRequest.
Types ¶
type AbsentEncodingPolicy ¶
type AbsentEncodingPolicy int
AbsentEncodingPolicy selects the response representation for requests that carry no Accept-Encoding header (or an empty one). RFC 7231 §5.3.4: an absent header signals no explicit client preference, and an empty value signals that no content-coding is wanted.
const ( // AbsentEncodingIdentity (zero value) serves the uncompressed // representation to requests without an Accept-Encoding header. Minimal // HTTP clients, health probes, and intermediaries that do not declare // support may not decompress a compressed response, so not compressing // is the safe default. AbsentEncodingIdentity AbsentEncodingPolicy = iota // AbsentEncodingFirstConfigured restores the v1.1.x behavior: requests // without an Accept-Encoding header receive the highest-priority // configured encoding. Use it only for deployments whose clients are // known to decompress every response. AbsentEncodingFirstConfigured )
func (AbsentEncodingPolicy) String ¶ added in v1.6.0
func (p AbsentEncodingPolicy) String() string
String returns the stable lowercase policy name for diagnostics and logs; unknown values render as AbsentEncodingPolicy(N).
type CORSConfig ¶
type CORSConfig struct {
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
ExposedHeaders []string
AllowCredentials bool
MaxAge int
AllowAllOrigins bool
OptionsPassthrough bool
// DenyUnmatched controls the behavior when a request origin does not
// match any entry in AllowedOrigins and AllowAllOrigins is false. When
// false (default), the middleware falls back to Access-Control-Allow-Origin: *,
// allowing all origins. When true, no Access-Control-Allow-Origin header is
// set, causing the browser to deny the cross-origin request.
DenyUnmatched bool
// AllowPrivateNetwork opts this origin into Chrome's Private Network
// Access / Local Network Access (LNA) check: when true, the middleware's
// preflight response carries Access-Control-Allow-Private-Network: true,
// which Chrome requires before a page from a less-private address space
// (public internet, private LAN) may fetch subresources that resolve to a
// more-private one (LAN, localhost). The header is set only on the
// middleware-generated preflight response, never on actual requests and
// never with OptionsPassthrough (there the handler owns the preflight), and
// it is sent unconditionally rather than echoed from the request so the
// behavior cannot silently break if Chrome changes its request-side
// signal. It is also independent of origin matching: a denied-origin
// preflight (DenyUnmatched, no ACAO) still carries the header — the
// browser already fails that response at the missing ACAO, so no
// capability is granted. Default false: enabling it grants cross-origin pages permission
// to reach this origin from a less-private network, which is an explicit
// security decision.
AllowPrivateNetwork bool
}
CORSConfig holds the configuration for CORS headers.
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig returns a permissive development-friendly CORS config that allows all origins.
func (CORSConfig) Validate ¶
func (c CORSConfig) Validate() error
Validate checks the CORSConfig for invalid combinations and returns an error describing the first issue found. A valid config can be used with CORS without causing browser-side CORS failures.
type CSRFConfig ¶
type CSRFConfig struct {
// CookieName is the name of the CSRF cookie.
// Default: "csrf_token"
CookieName string
// HeaderName is the request header containing the CSRF token.
// HTMX sends this header when configured with hx-headers.
// Default: "X-Csrf-Token" (case-insensitive on the wire)
HeaderName string
// FieldName is the form field name containing the CSRF token.
// Checked as fallback when the header is not present.
// Default: "csrf_token"
FieldName string
// MaxAge is the cookie max age.
// Default: 24 hours. A negative value fails Validate
// (csrf.max_age_negative); zero uses the default.
MaxAge time.Duration
// Secure sets the Secure flag on the cookie.
// Default: false. With SameSite=None, the constructor falls back to
// Secure=true (see AllowInsecureSameSiteNone) because browsers refuse to
// store SameSite=None cookies without Secure.
Secure bool
// SameSite sets the SameSite attribute on the cookie.
// Default: http.SameSiteLaxMode
SameSite http.SameSite
// Domain sets the cookie domain.
// Default: "" (host-only cookie)
Domain string
// Path sets the cookie path.
// Default: "/"
Path string
// TrustedOrigins configures origins allowed for cross-domain CSRF.
// Entries must be scheme://host origins; Validate rejects anything else
// (csrf.trusted_origin_invalid). Note: a wildcard host ("https://*")
// passes the shape gate but matches no real origin — dead config, not a
// bypass; list concrete origins instead.
// Default: nil (same-origin only)
TrustedOrigins []string
// TrustedProxies lists the IP addresses (or CIDR-notation networks) of
// reverse proxies that may strip/forward X-Forwarded-* and similar headers.
// Used by the plaintext-HTTP origin bypass: a request with no Origin/
// Referer/Sec-Fetch-Site header is only auto-marked as same-origin when
// the RemoteAddr is one of these trusted proxies (or loopback).
TrustedProxies []string
// TrustedProxiesCIDR is the parsed form of TrustedProxies CIDR entries.
// CSRFMiddleware populates it from TrustedProxies at construction time;
// Validate does not mutate the config. It may also be set directly.
TrustedProxiesCIDR []*net.IPNet
// BootLogUntrustedForwardedProto opts into one construction-time warning
// when TrustedProxies is empty: X-Forwarded-Proto is honored only from
// trusted proxies, so a deployment behind a TLS-terminating proxy that
// never lists the proxy silently gets no XFP trust path (its https
// Origin reads as a plaintext mismatch). The warning surfaces that
// combination at boot instead of at first CSRF failure. No effect when
// TrustedProxies is configured. Default: false.
BootLogUntrustedForwardedProto bool
// AllowPlaintextBypass grants the plaintext-HTTP origin bypass to ALL
// non-TLS requests when no TrustedProxies are configured.
// It is INSECURE for internet-facing plain-HTTP deployments.
AllowPlaintextBypass bool
// AllowInsecureSameSiteNone keeps a SameSite=None cookie without Secure
// instead of the constructor's Secure=true fallback. Current browsers
// refuse to store the insecure None cookie, so with this flag set every
// state-changing browser request fails CSRF validation. For legacy-client
// deployments and test rigs only. Validate reports the combination either
// way.
AllowInsecureSameSiteNone bool
// ErrorHandler is called when CSRF validation fails.
// Default: writes 403 Forbidden with plain text
ErrorHandler ErrorHandler
}
CSRFConfig configures CSRF protection.
All fields are optional; zero values use secure defaults. Uses justinas/nosurf internally for token generation, masking (BREACH mitigation), cookie management, and validation.
Example (SameSiteFallback) ¶
// SameSite=None without Secure produces a cookie current browsers refuse
// to store (rfc6265bis §5.7), so cookie-writing paths fall back to
// Secure=true while keeping the None intent. The deletion cookie here is
// emitted as if configured with Secure: true.
rec := httptest.NewRecorder()
InvalidateCSRFCookie(rec, CSRFConfig{SameSite: http.SameSiteNoneMode, Secure: false})
cookies := rec.Result().Cookies()
fmt.Println(cookies[0].Name, cookies[0].Secure, cookies[0].SameSite == http.SameSiteNoneMode)
Output: csrf_token true true
func (CSRFConfig) Validate ¶
func (c CSRFConfig) Validate() error
Validate checks the CSRF configuration for common misconfigurations. Returns a non-nil error if the config would produce insecure or broken behavior.
Validate is pure: it neither logs nor mutates the receiver. (Before the v1.0 cleanup it parsed TrustedProxies into TrustedProxiesCIDR as a side effect and warned about Secure=false; CSRFMiddleware now does both at construction time.)
type Capabilities ¶
type Capabilities struct {
// Hijacker is true when the writer implements http.Hijacker, allowing
// low-level connection takeover for WebSocket and similar upgrades.
Hijacker bool
// Flusher is true when the writer implements http.Flusher, allowing
// immediate flushing of buffered response data to the client.
Flusher bool
// Pusher is true when the writer implements http.Pusher, allowing
// HTTP/2 server pushes. Added in v1.9.0 (issue #47).
Pusher bool
}
Capabilities describes which optional http.ResponseWriter interfaces the underlying writer supports.
func DetectCapabilities ¶
func DetectCapabilities(w http.ResponseWriter) Capabilities
DetectCapabilities inspects w and reports which optional ResponseWriter interfaces it supports. Useful when composing middleware that needs to know whether operations like Hijack or Flush are available before attempting them.
Audit decision (2026-08-29): kept. It is not used by the middleware internals (each wrapper probes interfaces directly where needed), but it is exported public API for consumers composing their own ResponseWriter wrappers, classified Additive in docs/v1-stability.md (the struct was Frozen until the Pusher field joined in v1.9.0), and removing it would be a breaking change with no upside.
type Code ¶
type Code string
Code is a machine-readable error code in the httputil error taxonomy, e.g. "cors.max_age_negative" or "http.write_failed". Its prefix before the first dot is the Domain, identifying the failing component; the full code identifies the specific failure.
func CodeOf ¶
CodeOf returns the full machine-readable error code of err (e.g. "cors.max_age_negative"). It reports false when err carries no code (i.e. implements neither errorfamily.Coded nor a compatible ErrorCode method anywhere in its chain).
func (Code) Conflict ¶
func (c Code) Conflict(message string) *errorfamily.Error
Conflict returns a fresh Conflict-family error with this code.
func (Code) Corruption ¶
func (c Code) Corruption(message string) *errorfamily.Error
Corruption returns a fresh Corruption-family error with this code.
func (Code) Domain ¶
Domain returns the component prefix of the code: everything before the first dot, or the whole code when it contains no dot.
func (Code) Infrastructure ¶
func (c Code) Infrastructure(message string) *errorfamily.Error
Infrastructure returns a fresh Infrastructure-family error with this code.
func (Code) Orchestration ¶
func (c Code) Orchestration(message string) *errorfamily.Error
Orchestration returns a fresh Orchestration-family error with this code.
func (Code) Rejection ¶
func (c Code) Rejection(message string) *errorfamily.Error
Rejection returns a fresh Rejection-family error with this code. Rejection is the family for invalid configuration and unacceptable requests: retrying without changing the input cannot succeed.
func (Code) Transient ¶
func (c Code) Transient(message string) *errorfamily.Error
Transient returns a fresh Transient-family error with this code.
func (Code) WrapConflict ¶
func (c Code) WrapConflict(cause error, message string) *errorfamily.Error
WrapConflict wraps cause in a fresh Conflict-family error with this code.
func (Code) WrapCorruption ¶
func (c Code) WrapCorruption(cause error, message string) *errorfamily.Error
WrapCorruption wraps cause in a fresh Corruption-family error with this code.
func (Code) WrapInfrastructure ¶
func (c Code) WrapInfrastructure(cause error, message string) *errorfamily.Error
WrapInfrastructure wraps cause in a fresh Infrastructure-family error with this code.
func (Code) WrapOrchestration ¶
func (c Code) WrapOrchestration(cause error, message string) *errorfamily.Error
WrapOrchestration wraps cause in a fresh Orchestration-family error with this code.
func (Code) WrapRejection ¶
func (c Code) WrapRejection(cause error, message string) *errorfamily.Error
WrapRejection wraps cause in a fresh Rejection-family error with this code.
func (Code) WrapTransient ¶
func (c Code) WrapTransient(cause error, message string) *errorfamily.Error
WrapTransient wraps cause in a fresh Transient-family error with this code.
type CompressionConfig ¶
type CompressionConfig struct {
// MinSize is the minimum response body size (in bytes) before compression
// is attempted. Responses smaller than this are sent uncompressed.
MinSize int
// Level is the compression level passed to default factories when
// WriterFactories is not supplied. Ignored when WriterFactories is set.
// Valid range: gzip.HuffmanOnly to gzip.BestCompression, or
// gzip.DefaultCompression (-1).
//
// The zero value means "unset": Compression() treats Level == 0 as
// gzip.DefaultCompression, so a zero-value config compresses at the
// default level. A genuinely uncompressed response is not expressible
// through Level; use the identity encoding or skip the middleware.
Level int
// WriterFactories maps canonical encoding names to factory functions.
// The default set contains "gzip" and "deflate". Add entries such as
// "br" or "zstd" to enable brotli/zstd (the caller must provide a
// factory backed by the desired implementation).
//
// Built-in factory map is replaced entirely by the supplied map; copy
// defaults via DefaultWriterFactories() to extend rather than replace.
WriterFactories map[string]WriterFactory
// IncompressibleTypes is a list of content-type prefixes that should
// not be compressed (e.g., "image/", "video/"). When nil, the defaults
// from DefaultIncompressibleTypes() are used. Set to an empty slice to
// compress all content types.
IncompressibleTypes []string
// AbsentEncoding selects the response representation for requests that
// carry no Accept-Encoding header (or an empty one).
//
// The zero value is AbsentEncodingIdentity: the response is sent
// uncompressed. Set AbsentEncodingFirstConfigured to restore the v1.1.x
// behavior of compressing with the highest-priority configured encoding.
AbsentEncoding AbsentEncodingPolicy
}
CompressionConfig holds configuration for response compression.
The default config negotiates between gzip and deflate based on the client's Accept-Encoding header (q-values respected), compresses payloads >= 512 B, uses gzip's default level, and skips incompressible content types (images, video, audio, and pre-compressed application/* types).
To support encodings not bundled with this package (brotli, zstd, lz4), supply WriterFactory entries in WriterFactories. Encoding negotiation will include any registered encoding whose name appears in the Accept-Encoding header.
func DefaultCompressionConfig ¶
func DefaultCompressionConfig() CompressionConfig
DefaultCompressionConfig returns a CompressionConfig with sensible defaults for a typical JSON/text API: negotiates gzip/deflate, compresses payloads >= 512 B at gzip's default level.
func (CompressionConfig) Validate ¶
func (c CompressionConfig) Validate() error
Validate checks the CompressionConfig for invalid values. Level == 0 is accepted as the zero-value shorthand for gzip.DefaultCompression (see CompressionConfig.Level). The Level range check applies only when WriterFactories is empty — that is the only case where Level drives factory construction; with explicit factories, Level is ignored and is not validated, so configs that set both do not produce spurious warnings.
type DecompressionConfig ¶
type DecompressionConfig struct {
// Encodings specifies which request body encodings to decompress.
// Supported values: "gzip", "deflate". Empty = both (default).
Encodings []string
// MaxDecompressionSize limits the decompressed body size in bytes to
// prevent decompression bombs (zip bombs). Zero uses the 16 MiB default;
// there is no "unlimited" option. A negative value fails Validate
// (decompression.max_size_negative).
MaxDecompressionSize int64
}
DecompressionConfig holds the configuration for the Decompression middleware.
func DefaultDecompressionConfig ¶
func DefaultDecompressionConfig() DecompressionConfig
DefaultDecompressionConfig returns a DecompressionConfig that decompresses both gzip and deflate with a 16 MiB decompression size limit.
func (DecompressionConfig) Validate ¶
func (c DecompressionConfig) Validate() error
Validate checks the DecompressionConfig for invalid values.
type Domain ¶
type Domain string
Domain identifies the failing component of an error code: the prefix before the first dot (e.g. "cors" for "cors.max_age_negative"). Domains are by component, not by lifecycle — the errorfamily Family encodes lifecycle (Rejection, Transient, ...), the Domain answers "which middleware failed".
func DomainOf ¶
DomainOf returns the error-code domain of err: the component prefix of its machine-readable code. It reports false when err carries no code (i.e. implements neither errorfamily.Coded nor a compatible ErrorCode method anywhere in its chain).
Example ¶
cfg := DefaultCORSConfig()
cfg.MaxAge = -1
err := cfg.Validate()
if err != nil {
domain, ok := DomainOf(err)
fmt.Println(domain, ok)
}
Output: cors true
type ErrorHandler ¶
type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
ErrorHandler handles CSRF validation failures.
type HealthResponse ¶
type HealthResponse struct {
Status HealthStatus `json:"status"`
}
HealthResponse is the JSON response from a health check endpoint.
type HealthStatus ¶
type HealthStatus string
HealthStatus represents the status of a health check.
const ( // HealthStatusUp indicates the service is healthy. HealthStatusUp HealthStatus = "up" // HealthStatusDown indicates the service is unhealthy. HealthStatusDown HealthStatus = "down" )
type KeyExtractor ¶
KeyExtractor extracts a rate-limit key from an HTTP request. Return "" if the request should not be rate-limited (always allowed). Common extractors: RemoteAddr, header value, user ID from context.
Warning: if a custom KeyExtractor accidentally returns "" for every request, all clients share a single rate-limit bucket, effectively disabling per-client rate limiting. Use KeyExtractorFromRemoteAddr or KeyExtractorFromClientIP for safe defaults that never return "".
func KeyExtractorFromClientIP ¶
func KeyExtractorFromClientIP() KeyExtractor
KeyExtractorFromClientIP returns a KeyExtractor that uses ClientIP to resolve the real client IP, respecting X-Forwarded-For and X-Real-IP headers. Use this when deployed behind a trusted reverse proxy.
func KeyExtractorFromRemoteAddr ¶
func KeyExtractorFromRemoteAddr() KeyExtractor
KeyExtractorFromRemoteAddr returns a KeyExtractor that uses the request's RemoteAddr as the rate-limit key.
Caveat: RemoteAddr includes the client port, so the key is per TCP connection, not per client. HTTP connection pooling and churn (every new connection = a fresh bucket) make the effective budget much larger than the configured Limit; a client that opens a connection per request is effectively unlimited. For per-client-IP budgets use KeyExtractorFromClientIP instead.
func KeyExtractorFromTrustedClientIP ¶ added in v1.6.0
func KeyExtractorFromTrustedClientIP(cidrs []string) (KeyExtractor, error)
KeyExtractorFromTrustedClientIP returns a KeyExtractor that keys on the client IP with forwarded headers gated by the trusted-proxy CIDR set (see ParseTrustedProxies for the empty-slice default and the fail-loud CIDR contract). Use it instead of KeyExtractorFromClientIP whenever the deployment cannot guarantee that an outer proxy strips client-supplied forwarding headers.
type KeyedRateLimiter ¶
type KeyedRateLimiter struct {
// contains filtered or unexported fields
}
KeyedRateLimiter wraps rate-limiting middleware and exposes monitoring. Create one with NewKeyedRateLimiter when you need to track the number of active rate-limit keys via ActiveKeys.
Example (EvictionTTL) ¶
// EvictionTTL sweeps entries idle longer than the TTL on the next
// admission (lazy, no background goroutine). A one-nanosecond TTL makes
// the outcome deterministic without a fake clock: by the time the second
// key's Check runs, any real elapsed time exceeds the TTL, so the first
// key is always swept before the second is admitted. With MaxKeys unset
// the eviction here is purely TTL-driven, not capacity-driven.
limiter := NewKeyedRateLimiter(KeyedRateLimiterConfig{
Limit: 100,
Window: time.Minute,
TTL: time.Nanosecond,
KeyExtractor: KeyExtractorFromRemoteAddr(),
})
check := func(remote string) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = remote
limiter.Check(req)
}
check("10.0.0.1:1000")
before := limiter.ActiveKeys()
check("10.0.0.2:2000")
after := limiter.ActiveKeys()
// The first key went idle past the TTL while the second was in flight,
// so the tracked set never grows past one key despite no MaxKeys cap.
fmt.Println(before > 0, after == 1)
Output: true true
func NewKeyedRateLimiter ¶
func NewKeyedRateLimiter(cfg KeyedRateLimiterConfig) *KeyedRateLimiter
NewKeyedRateLimiter creates a KeyedRateLimiter with monitoring capabilities. Use this when you need to track the number of active rate-limit keys. For simple usage without monitoring, use KeyedRateLimiterMiddleware.
Example ¶
limiter := NewKeyedRateLimiter(KeyedRateLimiterConfig{
Limit: 100,
Window: time.Minute,
KeyExtractor: KeyExtractorFromRemoteAddr(),
MaxKeys: 2,
})
handler := limiter.Middleware()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
for _, remote := range []string{"10.0.0.1:1000", "10.0.0.1:2000", "10.0.0.1:3000"} {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = remote
handler.ServeHTTP(httptest.NewRecorder(), req)
}
// MaxKeys caps the tracked buckets: with the third distinct key the
// oldest-accessed bucket (10.0.0.1:1000) is evicted, keeping the memory
// footprint bounded no matter how many clients appear.
fmt.Println(limiter.ActiveKeys())
Output: 2
func (*KeyedRateLimiter) ActiveKeys ¶
func (rl *KeyedRateLimiter) ActiveKeys() int
ActiveKeys returns the number of currently tracked rate-limit keys.
func (*KeyedRateLimiter) Check ¶
func (rl *KeyedRateLimiter) Check(r *http.Request) (bool, string)
Check tests whether the request is allowed under the rate limit. Returns (true, "") if allowed, (false, retryAfter) if rejected.
Tokens are consumed at admission: the decision is instantaneous and request cancellation does not refund the consumed budget (see docs/planning/2026-08-29_21-30_rate-limiter-ctx-cancellation-design-note.md).
func (*KeyedRateLimiter) Middleware ¶
func (rl *KeyedRateLimiter) Middleware() func(http.Handler) http.Handler
Middleware returns the underlying middleware function.
type KeyedRateLimiterConfig ¶
type KeyedRateLimiterConfig struct {
// Limit is the maximum number of requests per Window.
Limit uint
// Window is the time period for which Limit applies.
Window time.Duration
// Burst is the maximum burst size (can be greater than Limit).
// Zero defaults to Limit.
Burst uint
// KeyExtractor produces the rate-limit key from a request.
// If nil, all requests share a single key —effectively a global rate limit.
// If an extractor returns empty string for a request, that request is
// exempt from rate limiting (always allowed).
KeyExtractor KeyExtractor
// TTL is how long an idle limiter entry is kept before eviction.
// Zero defaults to 10 minutes.
TTL time.Duration
// MaxKeys caps the number of tracked rate-limit keys.
// When exceeded, the oldest entry (by last access time) is evicted.
// The access stamp is refreshed on the slow path only, so a continuously
// hot key refreshes at most once per TTL; eviction victim choice is
// therefore approximate within one TTL window.
// Zero means no cap (unbounded growth).
MaxKeys uint
// OnAllowed is called when a request passes rate limiting.
OnAllowed func(r *http.Request)
// OnRejected is called when a request is rejected due to rate limiting.
// Contract: invoked synchronously on the request goroutine BEFORE the
// rejection response is written, so it must not block (it is on the hot
// path) and must not write to the ResponseWriter — RejectionHandler (or
// the built-in 429 writer) exclusively owns the response. Observers that
// need the response should hook RejectionHandler instead.
OnRejected func(r *http.Request, retryAfter string)
// RejectionHandler writes the response for rejected requests.
// Default: writes 429 Too Many Requests with Retry-After header.
RejectionHandler func(w http.ResponseWriter, r *http.Request, retryAfter string)
// Now returns the limiter's notion of the current time. It stamps entry
// last-use times, drives TTL eviction, and is handed to the underlying
// token bucket for refill math, so one injected clock controls the whole
// limiter — tests advance time deterministically instead of sleeping.
// Zero defaults to time.Now. The function must be safe for concurrent
// use: the limiter calls it on request goroutines.
Now func() time.Time
}
KeyedRateLimiterConfig configures the token-bucket rate limiter per key.
func DefaultKeyedRateLimiterConfig ¶
func DefaultKeyedRateLimiterConfig() KeyedRateLimiterConfig
DefaultKeyedRateLimiterConfig returns a KeyedRateLimiterConfig with sensible production defaults: 100 requests per minute per client IP, burst equal to the limit, 10-minute TTL for idle entries.
func (KeyedRateLimiterConfig) Validate ¶
func (c KeyedRateLimiterConfig) Validate() error
Validate checks the KeyedRateLimiterConfig for invalid values. Returns nil if the config is usable, or a descriptive error otherwise. The constructor (NewKeyedRateLimiter / KeyedRateLimiterMiddleware) calls Validate at construction time, but applies defaults first — so a direct Validate call catches zero-value Limit and Window errors that default-filling would mask.
Note: this method intentionally does NOT fill in defaults — validation is for catching user errors, not for silently coercing zero values. Defaults are applied by buildKeyedRateLimiter at middleware construction time. Burst=0 is allowed (it defaults to Limit at construction time), so the only fields that fail validation are those whose zero values would break rate calculation: Limit (must be > 0) and Window (must be > 0), and TTL (must not be negative; zero is valid and defaults to 10 minutes). Burst above math.MaxInt32 is rejected: the bucket size is converted to a signed int for golang.org/x/time/rate, which overflows on 32-bit platforms.
type LanguageConfig ¶ added in v1.6.0
type LanguageConfig struct {
// SupportedTags lists the canonical language tags the app serves, in
// priority order — the first entry is the default when nothing matches.
// Tags must be non-empty subtags of [a-zA-Z0-9-]. The declared spelling
// is preserved for serving ("zh-Hans" stays "zh-Hans" in
// Content-Language); comparisons are case-insensitive. Required.
SupportedTags []string
// DefaultTag is served when no extractor yields a matching candidate.
// Empty means SupportedTags[0].
DefaultTag string
// Extractors is the detection chain, tried in order; the first leg
// with candidates decides the negotiation input. Nil or empty means no
// extraction at all: every request negotiates to the default tag
// (valid for single-language sites that still want Content-Language
// and Vary stamped).
Extractors []LanguageExtractor
// Matcher resolves a candidate tag against the supported set and
// returns the supported tag to serve. Nil uses the built-in matcher:
// exact case-insensitive match first, then primary-subtag match
// ("de-AT" serves "de"). Supply a TagMatcher adapter for full BCP 47 /
// CLDR matching — see docs/integrations/x-text.md.
Matcher TagMatcher
// DisableContentLanguage turns off the Content-Language response
// header. The zero value keeps it on — the safe default.
DisableContentLanguage bool
// DisableVary turns off the Vary: Accept-Language response header.
// The zero value keeps it on (RFC-strict: the response varies with the
// request header even under cookie/query extraction legs).
DisableVary bool
}
LanguageConfig configures the Language middleware.
func DefaultLanguageConfig ¶ added in v1.6.0
func DefaultLanguageConfig() LanguageConfig
DefaultLanguageConfig returns a LanguageConfig with a working baseline: English only, Accept-Language extraction, both response headers on. Override SupportedTags and Extractors for real deployments.
func (LanguageConfig) Validate ¶ added in v1.6.0
func (c LanguageConfig) Validate() error
Validate checks the LanguageConfig for invalid values. The constructor (Language) calls Validate after applying defaults, following the validate-and-log pattern: invalid configs are logged and the middleware falls back to safe values instead of aborting construction.
type LanguageExtractor ¶ added in v1.6.0
LanguageExtractor extracts language-tag candidates from a request in preference order. An empty slice or ok=false means "no opinion" and the chain moves to the next extractor.
The list shape (rather than a single tag) is what makes Accept-Language negotiation correct: the top candidate may not match the supported set while a lower one does ("de-AT,de;q=0.9,en;q=0.8" against supported {en} must serve en).
func LanguageExtractorChain ¶ added in v1.6.0
func LanguageExtractorChain(extractors ...LanguageExtractor) LanguageExtractor
LanguageExtractorChain bundles extractors into one: legs run in order and the first leg that yields candidates decides the negotiation input. Nil legs are skipped, so a chain never panics on a dropped extractor.
func LanguageExtractorFromAcceptHeader ¶ added in v1.6.0
func LanguageExtractorFromAcceptHeader() LanguageExtractor
LanguageExtractorFromAcceptHeader parses the Accept-Language header with the RFC 7231 q-value grammar (the same allocation-free parser the compression negotiator uses) and yields the header's candidates in preference order: q descending, ties in listed order, q=0 excluded, "*" yielding nothing (the default-tag fallback covers it). A missing header yields no candidates.
func LanguageExtractorFromCookie ¶ added in v1.6.0
func LanguageExtractorFromCookie(name string) LanguageExtractor
LanguageExtractorFromCookie yields the tag stored in the named cookie, when present and non-empty. Cookie reading can fail per-cookie; a failed read is "no opinion", not an error — the chain continues.
func LanguageExtractorFromPathPrefix ¶ added in v1.6.0
func LanguageExtractorFromPathPrefix(prefixes map[string]string) LanguageExtractor
LanguageExtractorFromPathPrefix matches the request path against the given prefix→tag pairs ("/en" → "en") and yields the first pair whose prefix the path starts with. Match exactly the prefix or prefix+"/" so "/english" does not match "/en". The path leg is how SEO single-home funnels pin the journey regardless of headers.
func LanguageExtractorFromQuery ¶ added in v1.6.0
func LanguageExtractorFromQuery(param string) LanguageExtractor
LanguageExtractorFromQuery yields the tag in the given URL query parameter (e.g. "lang"), when present and non-empty.
type MaxBodySizeConfig ¶
type MaxBodySizeConfig struct {
// MaxBytes is the maximum request body size in bytes. Zero is valid but
// imposes a zero-byte limit: the reader rejects any non-empty body. There
// is no unlimited option; negative values fail Validate.
MaxBytes int64
}
MaxBodySizeConfig holds the configuration for the MaxBodySize middleware.
func DefaultMaxBodySizeConfig ¶
func DefaultMaxBodySizeConfig() MaxBodySizeConfig
DefaultMaxBodySizeConfig returns a MaxBodySizeConfig with a 1 MiB limit.
func (MaxBodySizeConfig) Validate ¶
func (c MaxBodySizeConfig) Validate() error
Validate checks the MaxBodySizeConfig for invalid values. Returns nil if the config is usable, or a descriptive error identifying the first issue found.
Validates:
- MaxBytes is non-negative (a negative limit is always a bug)
type MetricsConfig ¶
type MetricsConfig struct {
// Recorder receives one observation per request. Required.
Recorder MetricsRecorder
// PathFunc extracts the path to record from the request. If nil,
// r.URL.Path is used.
PathFunc func(r *http.Request) string
}
MetricsConfig holds configuration for the metrics recording middleware.
func DefaultMetricsConfig ¶
func DefaultMetricsConfig() MetricsConfig
DefaultMetricsConfig returns a config with sensible defaults. The caller must set Recorder before use.
func (MetricsConfig) Validate ¶
func (c MetricsConfig) Validate() error
Validate checks the MetricsConfig for invalid values.
type MetricsRecorder ¶
type MetricsRecorder interface {
// Record is called after each request completes with the HTTP method,
// path, response status code, and request duration.
Record(method, path string, status int, duration time.Duration)
}
MetricsRecorder receives one observation per request. Implementations must be safe for concurrent use.
type Middleware ¶
Middleware wraps an http.Handler to intercept or modify request flow.
func CORS ¶
func CORS(cfg CORSConfig) Middleware
CORS returns middleware that sets CORS headers based on the given config. Preflight OPTIONS requests receive a 204 No Content response unless OptionsPassthrough is set.
Example ¶
cfg := DefaultCORSConfig()
apiHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "api response")
})
handler := CORS(cfg)(apiHandler)
req := httptest.NewRequest(http.MethodOptions, "/test", nil)
req.Header.Set("Origin", "http://example.com")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
Output: 204
Example (PrivateNetwork) ¶
cfg := DefaultCORSConfig()
cfg.AllowPrivateNetwork = true
handler := CORS(cfg)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
// A Chrome Local Network Access preflight: OPTIONS with the request
// headers Chrome sends before fetching a more-private subresource. The
// middleware-generated preflight answers 204 and carries the LNA header;
// actual requests never do.
req := httptest.NewRequest(http.MethodOptions, "/", nil)
req.Header.Set("Origin", "https://public.example.com")
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
req.Header.Set("Access-Control-Allow-Private-Network", "true")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
fmt.Println(rec.Header().Get("Access-Control-Allow-Private-Network"))
Output: 204 true
func Compose ¶
func Compose(middlewares ...Middleware) Middleware
Compose combines middleware into a single middleware. The first middleware in the list becomes the outermost wrapper when the composed middleware is applied to a handler, matching Chain's ordering contract. Composing an empty list yields the identity middleware, which returns the handler unchanged.
Example ¶
// Composing an empty list yields the identity middleware: the handler
// passes through unchanged.
handler := Compose()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "ok")
}))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(rec.Code, rec.Body.String())
Output: 200 ok
Example (Ordered) ¶
// Middleware apply in declaration order: the first entry becomes the
// outermost wrapper.
addHeader := func(name, value string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(name, value)
next.ServeHTTP(w, r)
})
}
}
composed := Compose(
addHeader("X-Outer", "outer"),
addHeader("X-Inner", "inner"),
)
handler := composed(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "ok")
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(
rec.Code,
rec.Body.String(),
rec.Header().Get("X-Outer"),
rec.Header().Get("X-Inner"),
)
Output: 200 ok outer inner
func Compression ¶
func Compression(cfg CompressionConfig) Middleware
Compression returns middleware that compresses responses based on the client's Accept-Encoding header and the configured factory map. The negotiation respects RFC 7231 q-values.
If no compatible encoding is found, the response is sent uncompressed.
Example ¶
cfg := CompressionConfig{MinSize: 1, Level: -2}
helloHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("hello world"))
})
handler := Compression(cfg)(helloHandler)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Accept-Encoding", "gzip")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Header().Get("Content-Encoding"))
Output: gzip
Example (AbsentEncoding) ¶
build := func(policy AbsentEncodingPolicy) http.Handler {
cfg := CompressionConfig{MinSize: 1, AbsentEncoding: policy}
return Compression(cfg)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("hello world"))
}))
}
// A request without Accept-Encoding, served by both policies.
req := httptest.NewRequest(http.MethodGet, "/", nil)
// Default (AbsentEncodingIdentity): serve uncompressed.
rec := httptest.NewRecorder()
build(AbsentEncodingIdentity).ServeHTTP(rec, req)
fmt.Printf("%q\n", rec.Header().Get("Content-Encoding"))
// AbsentEncodingFirstConfigured: restore the pre-v1.2 behavior and pick
// the highest-priority configured encoding anyway.
rec2 := httptest.NewRecorder()
build(AbsentEncodingFirstConfigured).ServeHTTP(rec2, req)
fmt.Println(rec2.Header().Get("Content-Encoding"))
Output: "" gzip
func Decompression ¶
func Decompression(cfg DecompressionConfig) Middleware
Decompression returns middleware that decompresses request bodies based on the Content-Encoding header. Supported encodings: gzip, deflate.
The middleware wraps r.Body with the appropriate decompressor and removes the Content-Encoding and Content-Length headers from the request so downstream handlers see the decompressed body transparently.
To prevent decompression bombs, the decompressed body is limited to DecompressionConfig.MaxDecompressionSize bytes (default: 16 MiB). A decompression bomb attack sends a small compressed payload that decompresses to an enormous size, exhausting server memory.
Example ¶
var compressed bytes.Buffer
zw := gzip.NewWriter(&compressed)
_, _ = zw.Write([]byte("hello decompression"))
_ = zw.Close()
cfg := DefaultDecompressionConfig()
handler := Decompression(cfg)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
fmt.Println(string(body))
}))
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(compressed.Bytes()))
req.Header.Set("Content-Encoding", "gzip")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
Output: hello decompression
Example (MaxSize) ¶
var compressed bytes.Buffer
zw := gzip.NewWriter(&compressed)
_, _ = zw.Write([]byte("17 bytes payload"))
_ = zw.Close()
request := func(cfg DecompressionConfig, report func(n int, err error)) {
handler := Decompression(
cfg,
)(
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
report(len(body), err)
}),
)
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(compressed.Bytes()))
req.Header.Set("Content-Encoding", "gzip")
handler.ServeHTTP(httptest.NewRecorder(), req)
}
// The MaxDecompressionSize zero value selects the 16 MiB default; there
// is no unlimited option.
request(DecompressionConfig{}, func(n int, err error) {
fmt.Println(n, err == nil)
})
// A tiny limit trips bomb protection: the read fails once the
// decompressed body exceeds it.
request(DecompressionConfig{MaxDecompressionSize: 5}, func(_ int, err error) {
fmt.Println(err != nil)
})
Output: 16 true true
func Language ¶ added in v1.6.0
func Language(cfg LanguageConfig) Middleware
Language returns middleware that negotiates the request language, stores the served tag in the request context, and stamps Content-Language and Vary: Accept-Language (both on by default). Invalid configs follow the validate-and-log pattern: they are logged and the middleware falls back to safe values (see LanguageConfig).
Example ¶
cfg := DefaultLanguageConfig()
cfg.SupportedTags = []string{"en", "de"}
handler := Language(cfg)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "negotiated=%s", LanguageFromContext(r.Context()))
}))
req := httptest.NewRequest(http.MethodGet, "/", http.NoBody)
req.Header.Set("Accept-Language", "de-DE,de;q=0.9,en;q=0.8")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Header().Get("Content-Language"))
fmt.Println(rec.Header().Get("Vary"))
fmt.Print(rec.Body.String())
Output: de Accept-Language negotiated=de
func Logging ¶
func Logging(logger *slog.Logger) Middleware
Logging returns middleware that logs each request with method, path, status, and duration using the provided slog.Logger.
Example ¶
logger := slog.New(slog.DiscardHandler)
handler := Logging(logger)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
Output: 200
func LoggingFromContext ¶ added in v1.6.0
func LoggingFromContext(fallback *slog.Logger, fromContext func(context.Context) *slog.Logger) Middleware
LoggingFromContext returns middleware that resolves the slog.Logger for each request from the request context via fromContext, falling back to fallback when fromContext is nil or returns nil. When neither yields a logger the request is served without a log line, so deployments can scope logging per request (per tenant, per trace) instead of per handler. The logged attributes match Logging exactly.
func MaxBodySize ¶
func MaxBodySize(maxBytes int64) Middleware
MaxBodySize returns middleware that limits request body size to maxBytes. When the limit is exceeded, the underlying read returns an error and the connection is closed to prevent the client from sending more data. A maxBytes of zero or negative rejects any non-empty body (the empty body is allowed through); there is no unlimited option.
Handlers should check for errors from r.Body.Read and respond with http.StatusRequestEntityTooLarge (413) as appropriate.
Example ¶
handler := MaxBodySize(5)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(
http.MethodPost,
"/",
bytes.NewReader([]byte("this is way too long")),
)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
Output: 413
func MaxBodySizeMiddleware ¶
func MaxBodySizeMiddleware(cfg MaxBodySizeConfig) Middleware
MaxBodySizeMiddleware returns middleware that limits request body size using the provided configuration. The config is validated at construction time; invalid values are logged via slog and the middleware continues with the provided values.
func Metrics ¶
func Metrics(cfg MetricsConfig) Middleware
Metrics returns middleware that records request metrics via the configured MetricsRecorder. The middleware wraps the handler with a ResponseRecorder to capture the status code.
A nil Recorder is invalid; per the validate-and-log contract the constructor logs the misconfiguration and still builds a working middleware that serves requests without recording, instead of panicking on the first request.
Example ¶
recorder := &exampleMetricsRecorder{}
handler := Metrics(MetricsConfig{Recorder: recorder})(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusTeapot)
}),
)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/hello", nil))
fmt.Println(rec.Code, recorder.lastMethod, recorder.lastPath, recorder.lastStatus)
Output: 418 GET /hello 418
func Nonce ¶
func Nonce(cfg NonceConfig) Middleware
Nonce returns middleware that generates a per-request CSP nonce, stores it in the request context for template access, and optionally sets the Content-Security-Policy response header.
Example ¶
handler := Nonce(
DefaultNonceConfig(),
)(
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
// Use in templates: <script {{ NonceAttr }}>...</script>
fmt.Println(NonceAttr(r) != "")
}),
)
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Header().Get("Content-Security-Policy") != "")
Output: true true
func Recovery ¶
func Recovery(logger *slog.Logger) Middleware
Recovery returns middleware that catches panics in downstream handlers, logs the panic value and stack trace, and returns 500 Internal Server Error. Panics with the net/http sentinel http.ErrAbortHandler are re-panicked unchanged so the server's own silent connection-abort handling applies.
It is equivalent to RecoveryWithConfig with a nil OnPanic hook.
Example ¶
logger := slog.New(slog.DiscardHandler)
handler := Recovery(logger)(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
panic("test panic")
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
Output: 500
func RecoveryWithConfig ¶ added in v1.6.0
func RecoveryWithConfig(cfg RecoveryConfig) Middleware
RecoveryWithConfig returns panic-recovery middleware configured by cfg. Behavior matches Recovery; cfg.OnPanic additionally exposes the recovered value to observability integrations.
Example ¶
ExampleRecoveryWithConfig bridges panic recovery to an observability SDK. The hook runs after the panic is logged and before the 500 is written, so an active span (for example one created by otelhttp) is still open when it runs.
handler := RecoveryWithConfig(RecoveryConfig{
Logger: slog.New(slog.DiscardHandler),
OnPanic: func(r *http.Request, recovered any) {
// Bridge point: record the panic on the active span here, e.g.
// span.RecordError(...) and span.SetStatus(codes.Error, ...).
fmt.Printf("hook: %s %v\n", r.Method, recovered)
},
})(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic("boom")
}))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/orders", http.NoBody))
fmt.Println("status:", rec.Code)
fmt.Println("body:", rec.Body.String())
Output: hook: GET boom status: 500 body: Internal Server Error
func RequestID ¶
func RequestID(cfg RequestIDConfig) Middleware
RequestID returns middleware that propagates or generates a request ID. The ID is stored in the request context and set as a response header.
Example ¶
cfg := DefaultRequestIDConfig()
handler := RequestID(cfg)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := RequestIDFromContext(r.Context())
fmt.Println(id != "")
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
Output: true
func SecurityHeaders ¶
func SecurityHeaders(cfg SecurityHeadersConfig) Middleware
SecurityHeaders returns middleware that sets common security response headers based on the given configuration.
Example ¶
cfg := DefaultSecurityHeadersConfig()
handler := SecurityHeaders(
cfg,
)(
http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}),
)
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Header().Get("X-Content-Type-Options"))
Output: nosniff
func Timeout ¶
func Timeout(duration time.Duration) Middleware
Timeout returns middleware that enforces a deadline on the request context. If the handler does not complete within the given duration, the context is cancelled. The handler must respect context cancellation for this to work.
Example ¶
handler := Timeout(time.Second)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, ok := r.Context().Deadline()
fmt.Println(ok)
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
Output: true
type MiddlewareFunc ¶
MiddlewareFunc adapts an ordinary function to the Middleware signature so it can carry composition helpers. Middleware is an alias for a plain function type and therefore cannot declare methods; define reusable middleware functions as MiddlewareFunc to chain them fluently.
func (MiddlewareFunc) Then ¶
func (mw MiddlewareFunc) Then(next http.Handler) http.Handler
Then applies the middleware to next, returning the wrapped handler. A nil next wires a fallback handler that serves 500 for every request (even for a nil receiver), and a nil receiver with a non-nil next applies as the identity (nothing wraps next) — wiring mistakes surface as a diagnosable response instead of a panic — the library never panics by design.
Example ¶
// MiddlewareFunc lets a plain middleware function carry the Then method,
// so middleware and handler chain fluently without a call to Chain.
var addHeader MiddlewareFunc = func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Trace", "abc")
next.ServeHTTP(w, r)
})
}
handler := addHeader.Then(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "ok")
}))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(rec.Code, rec.Body.String(), rec.Header().Get("X-Trace"))
Output: 200 ok abc
type MiddlewareStack ¶
type MiddlewareStack struct {
// contains filtered or unexported fields
}
MiddlewareStack collects named middleware entries, validates their ordering, and builds the final handler chain. It prevents accidental duplication and enforces that MiddlewareRecovery is outermost when present.
The zero value is an empty stack ready for MiddlewareStack.Add; NewMiddlewareStack exists for explicitness at call sites.
Add is safe to call concurrently with reads (Names, Validate, Build, and the middleware returned by Middleware): every read observes an immutable snapshot of the entries published atomically by Add, so a stack can be extended while a handler built from an earlier snapshot is serving.
Example ¶
stack := NewMiddlewareStack()
if err := stack.Add(MiddlewareRequestID, RequestID(DefaultRequestIDConfig())); err != nil {
fmt.Println("error:", err)
return
}
if err := stack.Add(
MiddlewareSecurityHeaders,
SecurityHeaders(DefaultSecurityHeadersConfig()),
); err != nil {
fmt.Println("error:", err)
return
}
handler := stack.Build(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "ok")
}))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(rec.Code, rec.Body.String(), stack.Names())
Output: 200 ok [request-id security-headers]
func NewMiddlewareStack ¶
func NewMiddlewareStack() *MiddlewareStack
NewMiddlewareStack returns an empty stack ready for MiddlewareStack.Add.
func (*MiddlewareStack) Add ¶
func (s *MiddlewareStack) Add(name string, middleware Middleware) error
Add appends a named middleware to the stack. The first middleware added becomes the outermost wrapper when MiddlewareStack.Build is called. Returns an error if a middleware with the same name is already present, or if name is empty. Safe for concurrent use.
func (*MiddlewareStack) Build ¶
func (s *MiddlewareStack) Build(handler http.Handler) http.Handler
Build applies all middleware to the handler and returns the final handler. The first middleware added becomes the outermost wrapper. Does not call MiddlewareStack.Validate; call it separately to check ordering.
func (*MiddlewareStack) Middleware ¶
func (s *MiddlewareStack) Middleware() Middleware
Middleware returns the stack as a single composable middleware. Ordering matches MiddlewareStack.Build: the first middleware added is the outermost wrapper when the returned middleware is applied to a handler. Each application reads an immutable snapshot of the stack's entries, so middleware added after this call is included — and a snapshot being applied concurrently with an Add observes either the pre- or post-Add state, never a torn mixture.
func (*MiddlewareStack) Names ¶
func (s *MiddlewareStack) Names() []string
Names returns the names of all middleware in the stack, in order.
func (*MiddlewareStack) Validate ¶
func (s *MiddlewareStack) Validate() error
Validate checks for common ordering mistakes. Currently enforces that MiddlewareRecovery, when present, is the first (outermost) middleware.
type NonceConfig ¶
type NonceConfig struct {
// Size is the number of random bytes generated per request before base64
// encoding. A value of 0 uses the default (20 bytes / 160 bits). Minimum
// recommended: 16 (128 bits per CSP Level 3).
Size int
// CSPBuilder takes the generated base64-encoded nonce and returns the
// Content-Security-Policy header value. If nil, no CSP header is set —
// the nonce is only available via NonceFromContext/NonceFromRequest for
// template use. Default: RecommendedCSPWithNonce.
CSPBuilder func(nonce string) string
}
NonceConfig configures per-request CSP nonce generation and propagation.
func DefaultNonceConfig ¶
func DefaultNonceConfig() NonceConfig
DefaultNonceConfig returns a NonceConfig with sensible defaults: 20 random bytes (160 bits) and a CSP policy that allows self plus the nonce for script-src and style-src.
func (NonceConfig) Validate ¶
func (c NonceConfig) Validate() error
Validate checks the NonceConfig for invalid values. A Size of 0 means "use default" and is always valid. Any non-zero Size below 16 (128 bits) is rejected per the CSP Level 3 recommendation.
type RecoveryConfig ¶ added in v1.6.0
type RecoveryConfig struct {
// Logger receives the panic log line. A nil Logger falls back to
// [slog.Default].
Logger *slog.Logger
// OnPanic, when non-nil, runs after the panic is logged and before the
// 500 response is written. It is the bridge to observability SDKs: record
// the panic on the active span (for example with otel.RecordError)
// without adding a tracing dependency to this package.
//
// The hook runs synchronously on the request goroutine. A panic from the
// hook is logged and swallowed so it cannot replace the original panic
// handling; the 500 response is still written.
OnPanic func(r *http.Request, recovered any)
}
RecoveryConfig configures RecoveryWithConfig. Every field has a defined zero-value behavior, so there is no invalid configuration to validate.
type RequestIDConfig ¶
type RequestIDConfig struct {
ResponseHeader string
GenerateID func() string
IncomingHeader string
}
RequestIDConfig holds the configuration for the request ID middleware.
func DefaultRequestIDConfig ¶
func DefaultRequestIDConfig() RequestIDConfig
DefaultRequestIDConfig returns a RequestIDConfig that reads the X-Request-ID header and falls back to a generated 32-character time-ordered hex ID if not present. The generated ID is sortable by creation time, monotonic within a second, and unique across the process.
func (RequestIDConfig) Validate ¶
func (c RequestIDConfig) Validate() error
Validate checks the RequestIDConfig for invalid values.
type ResponseRecorder ¶
type ResponseRecorder struct {
http.ResponseWriter
// contains filtered or unexported fields
}
ResponseRecorder wraps an http.ResponseWriter to capture the status code. It also supports http.Flusher, http.Hijacker, and http.Pusher when the underlying ResponseWriter implements them (Push returns a classified error when it does not).
func NewResponseRecorder ¶
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder
NewResponseRecorder creates a ResponseRecorder that defaults to 200 OK.
Example ¶
inner := httptest.NewRecorder()
rec := NewResponseRecorder(inner)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(rec.Status())
Output: 404
Example (Unwritten) ¶
rec := NewResponseRecorder(httptest.NewRecorder())
// Status reports 0 before any WriteHeader call; WroteHeader distinguishes
// "no status set" from a real status of 0.
fmt.Println(rec.Status(), rec.WroteHeader())
handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(rec.Status(), rec.WroteHeader())
Output: 0 false 204 true
func (*ResponseRecorder) Flush ¶
func (r *ResponseRecorder) Flush()
Flush delegates to the underlying ResponseWriter if it implements http.Flusher.
func (*ResponseRecorder) HeaderSnapshot ¶
func (r *ResponseRecorder) HeaderSnapshot() http.Header
HeaderSnapshot returns a shallow copy of the response headers at the time of the call. Useful for inspecting headers after a handler has written them.
func (*ResponseRecorder) Hijack ¶
func (r *ResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack delegates to the underlying ResponseWriter if it implements http.Hijacker.
func (*ResponseRecorder) Push ¶ added in v1.9.0
func (r *ResponseRecorder) Push(target string, opts *http.PushOptions) error
Push delegates an HTTP/2 server push to the underlying ResponseWriter if it implements http.Pusher. Without an http.Pusher underneath it returns a classified http.push_unsupported error (Infrastructure, cause http.ErrNotSupported), so handlers keep the standard type-assert idiom: the recorder itself always satisfies http.Pusher.
func (*ResponseRecorder) Status ¶
func (r *ResponseRecorder) Status() int
Status returns the captured HTTP status code, or 0 if WriteHeader has not been called.
func (*ResponseRecorder) Write ¶
func (r *ResponseRecorder) Write(b []byte) (int, error)
Write implicitly sets status 200 if WriteHeader has not yet been called.
func (*ResponseRecorder) WriteHeader ¶
func (r *ResponseRecorder) WriteHeader(code int)
WriteHeader captures the status code and delegates to the underlying ResponseWriter.
func (*ResponseRecorder) WroteHeader ¶
func (r *ResponseRecorder) WroteHeader() bool
WroteHeader reports whether WriteHeader has been called.
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
// ContentTypeNosniff sets X-Content-Type-Options to "nosniff" when true.
// Legacy bool field — prefer ContentTypeOptions for full control.
ContentTypeNosniff bool
// ContentTypeOptions sets X-Content-Type-Options to an explicit value.
// Takes precedence over ContentTypeNosniff. Set to SecurityHeaderSkip
// to suppress the header.
ContentTypeOptions string
FrameOptions string
StrictTransportSecurity string
ReferrerPolicy string
ContentSecurityPolicy string
// PermissionsPolicy sets the Permissions-Policy header.
PermissionsPolicy string
// Custom headers are applied after all other headers.
Custom map[string]string
}
SecurityHeadersConfig holds the configuration for security response headers.
func DefaultSecurityHeadersConfig ¶
func DefaultSecurityHeadersConfig() SecurityHeadersConfig
DefaultSecurityHeadersConfig returns a SecurityHeadersConfig with sensible production defaults.
func (SecurityHeadersConfig) Validate ¶
func (c SecurityHeadersConfig) Validate() error
Validate checks the SecurityHeadersConfig for invalid values. Returns nil if the config is usable, or a descriptive error otherwise.
FrameOptions is the only field with constrained values: it must be empty (no header sent), "DENY", "SAMEORIGIN", or SecurityHeaderSkip ("-") — anything else produces an invalid X-Frame-Options header per RFC 7034 §2.1.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps an http.Server with lifecycle helpers.
Example ¶
srv, err := NewServer(ServerConfig{
Addr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "hello")
}))
if err != nil {
fmt.Println("error:", err)
return
}
srv.Start()
addr, ok := func() (string, bool) {
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
if listenAddr, listening := srv.ListenerAddr(); listening {
return listenAddr.String(), true
}
time.Sleep(time.Millisecond)
}
return "", false
}()
if !ok {
fmt.Println("server did not start")
return
}
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodGet,
"http://"+addr+"/",
nil,
)
if err != nil {
fmt.Println("error:", err)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("error:", err)
return
}
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(resp.StatusCode, string(body))
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
fmt.Println("error:", err)
}
Output: 200 hello
func NewServer ¶
func NewServer(cfg ServerConfig, handler http.Handler) (*Server, error)
NewServer creates a new Server with the given configuration and handler. The handler is typically a *http.ServeMux or a middleware-wrapped handler.
func NewServerListener ¶ added in v1.7.0
func NewServerListener(listener net.Listener, cfg ServerConfig, handler http.Handler) (*Server, error)
NewServerListener creates a Server that serves on an already-bound listener instead of binding its own. It is the composition seam for wrappers that need to own the bind: synchronous bind-failure classification, readiness state observable before serving starts, or pre-serve startup hooks that inspect the bound address. All Server lifecycle semantics apply unchanged: Start and StartTLS serve on the injected listener (they never bind), Shutdown drains in-flight requests and closes it, and ListenerAddr reports the injected listener from construction onward.
cfg.Addr is derived from listener.Addr().String() because the bound listener is the authority on the address; every other ServerConfig field applies as with NewServer. On success the Server owns the listener: net/http's Serve closes it when serving ends, so a Server built here serves its listener exactly once — a later Start or StartTLS after the first serve finished returns the classified server.listener_consumed rejection instead of rebinding. Create a new Server (and listener) to serve again. On error, the listener is untouched and remains the caller's to close.
Example ¶
// Bind the listener yourself: bind failures are classified at this call,
// and the bound address is observable before any serving starts.
listener, err := new(net.ListenConfig).Listen(context.Background(), "tcp", "127.0.0.1:0")
if err != nil {
fmt.Println("error:", err)
return
}
srv, err := NewServerListener(listener, ServerConfig{
ShutdownTimeout: time.Second,
}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "injected")
}))
if err != nil {
fmt.Println("error:", err)
return
}
srv.Start()
// ListenerAddr reports the injected listener from construction, so no
// start-polling is needed: readiness is synchronous because the caller
// owns the bind.
addr, _ := srv.ListenerAddr()
req, reqErr := http.NewRequestWithContext(
context.Background(),
http.MethodGet,
"http://"+addr.String()+"/",
nil,
)
if reqErr != nil {
fmt.Println("error:", reqErr)
return
}
resp, doErr := http.DefaultClient.Do(req)
if doErr != nil {
fmt.Println("error:", doErr)
return
}
body, readErr := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if readErr != nil {
fmt.Println("error:", readErr)
return
}
fmt.Println(resp.StatusCode, string(body))
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
fmt.Println("error:", err)
}
Output: 200 injected
func (*Server) Addr ¶
Addr returns the configured listen address (e.g. ":8080" or ":0"); it is not rewritten when the OS picks an ephemeral port, so use ListenerAddr for the resolved address of the active listener. For a Server built by NewServerListener the value is derived from the injected listener at construction, not caller configuration.
func (*Server) ListenerAddr ¶
ListenerAddr returns the resolved network address of the active listener (useful after binding an ephemeral port such as ":0"), and false when the server is not currently listening (failed to bind, or shut down; for a Server that binds its own listener, also before Start is called). A Server built by NewServerListener reports its injected listener from construction onward, because the listener exists before serving starts.
func (*Server) Shutdown ¶
Shutdown gracefully shuts down the server. If the provided context has no deadline and the server was configured with a ShutdownTimeout, a timeout context is derived automatically to prevent indefinite hangs.
Shutting down a Server that was never started is a no-op that returns nil: nothing was served, so for a Server built by NewServerListener the caller's listener stays open, addressable via ListenerAddr, and still servable by a later Start or StartTLS. Passing the call through to net/http instead would poison the shared http.Server — it marks itself shut down on any Shutdown call, and a later Serve would return ErrServerClosed at once, silently.
func (*Server) Start ¶
Start begins listening on the configured address in a goroutine. It returns a channel that receives any non-shutdown error from Serve; a bind failure (e.g. address already in use) is delivered immediately. Use ListenerAddr to resolve ephemeral ports after a ":0" address. For a Server built by NewServerListener, no bind happens: Start serves on the injected listener instead.
Error delivery implies full failure settlement: the listener is closed and ListenerAddr reports false before the error can be received, so the same Server can be started again after any failure (bind error, Serve error) without re-creating it. Starting a server that is currently listening returns the classified server.already_started error instead of binding an untracked orphan listener; that rejection leaves the server running and does not affect a later Start after Shutdown or a failure.
func (*Server) StartTLS ¶
StartTLS begins listening on the configured address for HTTPS in a goroutine, using the certificate and key files at the given paths. The server's TLSConfig (validated to enforce TLS 1.2+ when set) applies to the listener. It returns a channel that receives any non-shutdown error from Serve; a bind failure (e.g. address already in use) is delivered immediately. Use ListenerAddr to resolve ephemeral ports after a ":0" address.
The same settlement guarantee as Start applies: a delivered error (including a ServeTLS failure such as unreadable certificate files) implies the listener is already closed and ListenerAddr reports false, so retrying StartTLS on the same Server after a failure is safe. A start while listening returns the classified server.already_started error.
With in-memory certificates, pass empty paths and set TLSConfig.GetCertificate (or Certificates) on the ServerConfig instead. For a Server built by NewServerListener, no bind happens: StartTLS wraps and serves on the injected listener instead.
type ServerConfig ¶
type ServerConfig struct {
Addr string
TLSConfig *tls.Config
ReadTimeout time.Duration
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
ShutdownTimeout time.Duration
}
ServerConfig holds the configuration for an HTTP server.
func DefaultServerConfig ¶
func DefaultServerConfig() ServerConfig
DefaultServerConfig returns a ServerConfig with sensible production defaults.
func (ServerConfig) Validate ¶
func (c ServerConfig) Validate() error
Validate checks the ServerConfig for invalid values. Returns nil if the config is usable, or a descriptive error identifying the first issue found.
Validates:
- Addr is non-empty (empty Addr would bind to a random port — usually a bug)
- All timeouts are non-negative
- ReadHeaderTimeout <= ReadTimeout (the underlying http.Server enforces this internally; checking here surfaces the misconfiguration clearly)
- TLSConfig.MinVersion (when set) is at least TLS 1.2 (RFC 8996 deprecates TLS 1.0/1.1; a zero MinVersion defaults to TLS 1.2 in Go 1.18+, which is safe)
type TagMatcher ¶ added in v1.6.0
TagMatcher resolves one candidate tag against the app's supported set and returns the supported tag to serve. Return ok=false to pass — the middleware then tries the next candidate and finally the default tag. The built-in matcher is exact-then-primary-subtag; supply an adapter for full BCP 47 / CLDR matching (golang.org/x/text's language.Matcher, see docs/integrations/x-text.md). Matchers must be safe for concurrent use.
type TrustedProxySet ¶ added in v1.6.0
type TrustedProxySet struct {
// contains filtered or unexported fields
}
TrustedProxySet is a parsed, immutable set of trusted proxy networks. A value from ParseTrustedProxies with no entries trusts loopback only; the zero value trusts nothing (no peer's forwarded headers are honored). The value is safe for concurrent use: the parsed networks never change after ParseTrustedProxies returns.
func ParseTrustedProxies ¶ added in v1.6.0
func ParseTrustedProxies(cidrs []string) (TrustedProxySet, error)
ParseTrustedProxies parses CIDR entries into a TrustedProxySet. An empty or nil slice substitutes the loopback-only default (127.0.0.0/8, ::1/128), so local proxies and httptest clients work without configuration; remote trusts require explicit entries. An entry net.ParseCIDR rejects fails the whole call (classified Rejection) instead of silently narrowing the trust set: a typo'd CIDR would otherwise collapse every client onto the proxy's address, one shared rate-limit bucket.
func (TrustedProxySet) ClientIP ¶ added in v1.6.0
func (s TrustedProxySet) ClientIP(r *http.Request) string
ClientIP resolves the client IP with the trust gate applied. Forwarded headers are read only when the socket peer is inside the trust set; otherwise the RemoteAddr host wins. The X-Forwarded-For list is walked right-to-left, skipping trusted proxies, so an attacker-supplied leftmost entry cannot outrank the entry an honest appending proxy placed after it. A malformed list is distrusted as a whole. The result is never empty when RemoteAddr is set.
func (TrustedProxySet) Contains ¶ added in v1.6.0
func (s TrustedProxySet) Contains(ip net.IP) bool
Contains reports whether ip is inside the trust set. The zero TrustedProxySet contains nothing, so it trusts no peer.
func (TrustedProxySet) KeyExtractor ¶ added in v1.6.0
func (s TrustedProxySet) KeyExtractor() KeyExtractor
KeyExtractor returns a KeyExtractor keyed on the trusted-proxy-gated client IP (TrustedProxySet.ClientIP). The extractor never returns "", so a miswired trust set cannot collapse all clients into one bucket.
type WriterFactory ¶
type WriterFactory func(dst io.Writer) (io.WriteCloser, error)
WriterFactory creates a fresh streaming writer that compresses bytes written to it and writes them to dst. Implementations are responsible for buffering and finalization. The returned writer must be Close()d by the caller to flush pending compressed bytes.
The factory is called once per response. Implementations may be expensive to construct; consider pooling if hot.
func DeflateWriterFactory ¶
func DeflateWriterFactory(level int) WriterFactory
DeflateWriterFactory returns a WriterFactory backed by compress/flate (raw deflate stream, no zlib header) at the given level. Browsers expecting "deflate" almost always tolerate raw deflate, but some older proxies required zlib-wrapped deflate; raw deflate is the HTTP-standard form.
func GzipWriterFactory ¶
func GzipWriterFactory(level int) WriterFactory
GzipWriterFactory returns a WriterFactory backed by compress/gzip at the given level (gzip.DefaultCompression, gzip.BestSpeed, etc.).
Source Files
¶
- capabilities.go
- clientip.go
- code.go
- compose.go
- compress_content_type.go
- compress_pool.go
- compress_writer.go
- compress_writer_compress.go
- compression.go
- compression_negotiator.go
- compression_qvalue.go
- context.go
- cors.go
- csrf.go
- decompression.go
- doc.go
- errors.go
- headers.go
- health.go
- hex.go
- id_generator.go
- language.go
- logging.go
- maxbodysize.go
- metrics.go
- nonce.go
- queryparam.go
- ratelimit_keyed.go
- ratelimit_keyed_trusted.go
- recorder.go
- recovery.go
- requestid.go
- security.go
- server.go
- stack.go
- timeout.go
- wrapper.go
Directories
¶
| Path | Synopsis |
|---|---|
|
endpoints
module
|
|
|
Package httpspec provides a reusable suite of HTTP behavior specifications.
|
Package httpspec provides a reusable suite of HTTP behavior specifications. |
|
scripts
|
|
|
coverage-threshold
command
|
|
|
doc-snippet-refs
command
doc-snippet-refs checks that Go code fences in markdown docs only reference exported symbols that actually exist in this workspace's packages.
|
doc-snippet-refs checks that Go code fences in markdown docs only reference exported symbols that actually exist in this workspace's packages. |
|
server_timing
module
|