httputil

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 31 Imported by: 16 modules, 18 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httputil

Go Reference Go Version Coverage govulncheck License

Composable HTTP middleware, utility primitives, and server lifecycle helpers for Go — CORS, client IP extraction, response recording, middleware chaining, security headers, CSP nonce support, request ID, panic recovery, timeout enforcement, structured logging, response compression, request body decompression with bomb protection, ETag conditional requests (via go-etag composition), W3C Server-Timing, CSRF protection (nosurf), keyed rate limiting, content-language negotiation, configurable HTTP server, standard health checks, and — from the separate endpoints module — a self-describing /endpoints route listing.

Minimal footprint — four dependencies (go-error-family + go-etag same-author, golang.org/x/time, justinas/nosurf). Pure stdlib net/http. Go 1.27+ (the go directive requires 1.27.1+ since go-etag v0.5.0).

Install

go get github.com/larsartmann/httputil

Quick Start

package main

import (
    "log/slog"
    "net/http"
    "time"

    "github.com/larsartmann/httputil"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        requestID, _ := httputil.RequestIDFromContext(r.Context())
        slog.Info("handled", "path", r.URL.Path, "request_id", requestID)
        w.WriteHeader(http.StatusOK)
    })

    handler := httputil.Chain(
        mux,
        httputil.Recovery(slog.Default()),
        httputil.Logging(slog.Default()),
        httputil.Timeout(30 * time.Second),
        httputil.RequestID(httputil.DefaultRequestIDConfig()),
        httputil.SecurityHeaders(httputil.DefaultSecurityHeadersConfig()),
        httputil.CORS(httputil.DefaultCORSConfig()),
    )

    http.ListenAndServe(":8080", handler)
}

Features

CORS Middleware

Configurable Cross-Origin Resource Sharing with sensible defaults.

// Permissive config for local development (allows all origins)
handler := httputil.CORS(httputil.DefaultCORSConfig())(mux)

// Restrict to specific origins in production
cfg := httputil.CORSConfig{
    AllowedOrigins:   []string{"https://myapp.com", "*.example.com"},
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE"},
    AllowedHeaders:   []string{"Content-Type", "Authorization"},
    AllowCredentials: true,
    MaxAge:           3600,
}
handler := httputil.CORS(cfg)(mux)

Preflight OPTIONS requests receive 204 No Content automatically. Set OptionsPassthrough to forward them to your handler instead. Wildcard patterns like *.example.com match subdomains. Set AllowPrivateNetwork: true to answer Chrome's Local Network Access preflights with Access-Control-Allow-Private-Network: true (needed when pages from a less-private network fetch LAN or localhost subresources).

Use cfg.Validate() to catch invalid configurations at startup (e.g., AllowCredentials: true with AllowAllOrigins: true which browsers reject).

Client IP Extraction

Extracts the real client IP behind reverse proxies using standard header precedence.

func handler(w http.ResponseWriter, r *http.Request) {
    ip := httputil.ClientIP(r)
    fmt.Fprintf(w, "Your IP: %s", ip)
}

Resolution order: X-Forwarded-For (first entry) → X-Real-IP → RemoteAddr.

Security: ClientIP trusts proxy headers without validation. Only use behind a reverse proxy that strips or overwrites these headers.

Context helpers are available for downstream access:

handler := httputil.ClientIPMiddleware(next)
// In downstream handler:
ip := httputil.ClientIPFromContext(r.Context())
Response Recording

Wraps http.ResponseWriter to capture the status code for logging, metrics, or auditing.

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        rec := httputil.NewResponseRecorder(w)
        next.ServeHTTP(rec, r)
        log.Printf("%s %s → %d", r.Method, r.URL.Path, rec.Status())
    })
}

ResponseRecorder transparently supports http.Flusher, http.Hijacker, and http.Pusher when the underlying writer implements them (a Push against a writer without http.Pusher returns a classified http.push_unsupported error instead of silently dropping the capability). Write errors carry classified error codes via go-error-family for retry decisions.

HeaderSnapshot() returns an isolated copy of response headers for inspection:

headers := rec.HeaderSnapshot()
Middleware Chaining

Compose multiple middleware into a single handler. First middleware in the list is outermost.

handler := httputil.Chain(
    mux,
    httputil.CORS(httputil.DefaultCORSConfig()),
    authMiddleware,
    loggingMiddleware,
)
// Execution: CORS → auth → logging → mux
Behavioral Spec Suite

Validate any http.Handler against standard HTTP conventions with a single call. The httpspec subpackage runs 19 behavioral specs as parallel subtests.

import "github.com/larsartmann/httputil/httpspec"

func TestHTTPBehavior(t *testing.T) {
    t.Parallel()
    httpspec.Run(t, handler)
}

Specs checked: index page reachability, unknown path 404s, long URL handling, POST safety, Content-Type on bodies and errors, HEAD/OPTIONS/TRACE/CONNECT handling, redirect Location correctness, no duplicate headers, Accept header handling, no leaked internals, no Server version fingerprinting, no X-Powered-By header, X-Content-Type-Options: nosniff presence, no injection-header reflection (a client-supplied X-CSRF-Token/probe header value must never be echoed back in a response header). Opt-in spec families add targeted contract checks — httpspec.LanguageSpecs() pins that language-negotiating handlers stamp Content-Language and list Accept-Language in Vary, while httpspec.TracingSpecs() pins W3C trace-context tolerance (a valid traceparent or tracestate never causes a 5xx; a malformed one behaves like an absent header). httpspec.RunTracing(t, middleware) goes further and verifies the middleware layer itself: header and r.Pattern passthrough, absent-header invariance, request invariance (method/path/body), response passthrough, and Flusher/Pusher/Hijacker preservation. Use RunSerial for handlers with shared state. Skip inapplicable specs or add custom ones:

httpspec.Run(t, handler,
    httpspec.SkipSpec(httpspec.SpecNameUnknownPathReturns404), // SPA fallback
    httpspec.WithExtraSpecs(httpspec.Spec{
        Name:     "GET /health returns 200",
        Category: httpspec.CategoryRouting,
        Check:    httpspec.ExpectStatus(http.MethodGet, "/health", http.StatusOK),
    }),
)
Security Headers

Sets common security response headers with sensible defaults.

handler := httputil.SecurityHeaders(httputil.DefaultSecurityHeadersConfig())(mux)

Headers set by default: X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin.

CSP Nonce

Generates a per-request cryptographic nonce for Content Security Policy, allowing specific inline <script> and <style> elements to execute while blocking all others — no 'unsafe-inline' needed.

handler := httputil.Nonce(httputil.DefaultNonceConfig())(mux)

Retrieve the nonce in handlers or templates:

// In a handler:
nonce := httputil.NonceFromRequest(r)

// In a Go template:
//   <script {{ NonceAttr }}>...</script>
//   <style {{ NonceAttr }}>...</style>
attr := httputil.NonceAttr(r) // returns nonce="abc123"

Two built-in CSP builders:

  • RecommendedCSPWithNonce (default): script-src and style-src with nonce.
  • ProductionCSPWithNonce: adds object-src 'none', base-uri 'self', frame-ancestors 'none'.
cfg := httputil.DefaultNonceConfig()
cfg.CSPBuilder = httputil.ProductionCSPWithNonce // stricter policy
handler := httputil.Nonce(cfg)(mux)

Use a custom CSP by setting CSPBuilder, or set it to nil to disable the header entirely (context-only mode for when you set CSP elsewhere).

Ordering: Place Nonce after SecurityHeaders in the chain so the nonce-bearing CSP overwrites any static CSP. The default SecurityHeadersConfig does not set a CSP, so there is no conflict unless you explicitly set ContentSecurityPolicy in both.

Caching: Responses with per-request nonces must not be cached — a cached page would serve a stale nonce that no longer matches the CSP header. Set Cache-Control: no-store in your handler or caching middleware when using nonce-based CSP.

Request ID

Propagates or generates a request ID per request.

handler := httputil.RequestID(httputil.DefaultRequestIDConfig())(mux)
// Access in downstream handlers:
id := httputil.RequestIDFromContext(r.Context())
Panic Recovery

Catches panics, logs the stack trace, and returns 500 Internal Server Error.

handler := httputil.Recovery(slog.Default())(mux)

RecoveryWithConfig adds a nil-default OnPanic hook for observability integrations. It runs after the panic is logged and before the 500 is written — late enough to know the panic happened, early enough for the span to still be recording:

handler := httputil.RecoveryWithConfig(httputil.RecoveryConfig{
	Logger: logger,
	OnPanic: func(r *http.Request, recovered any) {
		span := trace.SpanFromContext(r.Context())
		span.RecordError(fmt.Errorf("panic: %v", recovered))
		span.SetStatus(codes.Error, "panic")
	},
})(mux)

A hook that panics is logged and swallowed, so a buggy integration cannot replace the recovery path. Recovery(logger) is exactly RecoveryWithConfig{Logger: logger} and is unchanged. Full OpenTelemetry wiring: docs/integrations/otel.md.

Request Timeout

Enforces a deadline on the request context. The handler must respect context cancellation.

handler := httputil.Timeout(30 * time.Second)(mux)
Structured Logging

Logs each request with method, path, status, duration, and client IP.

handler := httputil.Logging(slog.Default())(mux)

For per-request loggers (per tenant, per trace), resolve the logger from the request context instead; requests whose context carries no logger fall back to the given logger, and requests with neither are served without a log line:

handler := httputil.LoggingFromContext(slog.Default(), LoggerFromContext)(mux)
Response Compression

Transparent response compression negotiated from the client's Accept-Encoding header. Supports gzip and deflate out of the box, respects RFC 7231 q-values, and leaves small responses, non-2xx statuses, and already-encoded responses uncompressed. Requests without an Accept-Encoding header are served uncompressed by default (minimal clients and probes may not decompress); set AbsentEncoding: httputil.AbsentEncodingFirstConfigured to restore the pre-v1.2 behavior of compressing for header-less clients. Vary: Accept-Encoding is added to every response — compressed or not — so shared caches key on the negotiation instead of serving a compressed representation to a client that cannot decode it. Requests carrying a Range header always pass through uncompressed — byte-offset responses must be the verbatim representation, so compressing them would break range semantics.

handler := httputil.Compression(httputil.DefaultCompressionConfig())(mux)

Use cfg.Validate() to catch invalid configurations at startup (e.g., invalid compression levels or negative minimum sizes).

To add encodings not bundled with this package (brotli, zstd, lz4), register a WriterFactory:

cfg := httputil.DefaultCompressionConfig()
cfg.WriterFactories["br"] = func(dst io.Writer) (io.WriteCloser, error) {
    return brotli.NewWriterLevel(dst, brotli.DefaultCompression), nil
}
handler := httputil.Compression(cfg)(mux)

DefaultWriterFactories() returns a fresh map with gzip, deflate, and identity entries so you can extend rather than replace the built-ins.

Request Body Decompression

Transparently decompresses request bodies based on the Content-Encoding header. Supports gzip and deflate. The middleware replaces r.Body with a decompressing reader and removes Content-Encoding and Content-Length headers so downstream handlers see the decompressed body transparently.

handler := httputil.Decompression(httputil.DefaultDecompressionConfig())(mux)

Bomb protection: The decompressed body is limited to MaxDecompressionSize bytes (default: 16 MiB) to prevent decompression bomb attacks. When the limit is exceeded, reads return an error and the underlying reader is closed immediately. 0 is not an off switch: it selects the same 16 MiB default, so bomb protection cannot be accidentally disabled.

Restrict which encodings are accepted by setting Encodings:

cfg := httputil.DecompressionConfig{
    Encodings:            []string{"gzip"}, // deflate-only servers skip this
    MaxDecompressionSize: 1 << 20,           // 1 MiB limit
}
handler := httputil.Decompression(cfg)(mux)

Use cfg.Validate() to catch invalid configurations at startup (e.g., negative MaxDecompressionSize).

ETag / Conditional Requests

ETag generation and If-None-Match handling via the go-etag module. The middleware buffers GET/HEAD response bodies, computes an FNV-64a hash, and returns 304 Not Modified when the client's If-None-Match matches.

Pair ETags with explicit Cache-Control; without Vary on negotiated representations, caches may serve mismatched bodies. Cache policy belongs to the application (or a header middleware), conditional-request semantics to go-etag.

import "github.com/larsartmann/go-etag"

handler := etag.New(etag.DefaultETagConfig())(mux)

For domain types (etag.ETag, etag.ParseETag, etag.MatchesIfNoneMatch, etc.), import go-etag directly. etag.New returns func(http.Handler) http.Handler, which composes directly with Chain and MiddlewareStack.

Ready-made counters for go-etag's observability hooks (OnETagGenerated, On304, OnBufferOverflow) live in go-etag itself: github.com/larsartmann/go-etag/metrics (metrics.Attach(cfg) returns the config plus atomic counters with a HitRatio() accessor). The package moved out of this repo (it shipped here briefly as the etagmetrics sub-module in v1.3.0) to live next to the hooks it counts.

HTTP Server

A configurable http.Server wrapper with sensible timeout defaults and lifecycle helpers. Errors from Start/StartTLS arrive only after the failure is fully settled (listener closed, ListenerAddr reports not-listening), so restarting the same server after a failure is always safe; starting a listening server returns the classified server.already_started error instead of binding an orphan listener.

cfg := httputil.DefaultServerConfig()
cfg.Addr = ":8080"

srv, err := httputil.NewServer(cfg, handler)
if err != nil {
    log.Fatal(err)
}

errChan := srv.Start()

// Wait for shutdown signal, then call srv.Shutdown(ctx).

// HTTPS: srv.StartTLS("cert.pem", "key.pem") applies cfg.TLSConfig (TLS 1.2+ enforced).

Wrappers that need to own the bind (synchronous bind-failure classification, readiness observable before serving, socket-activated or unix-socket listeners) inject an already-bound listener instead:

ln, err := net.Listen("tcp", "127.0.0.1:0") // bind failures classify HERE, synchronously
if err != nil {
    log.Fatal(err)
}

srv, err := httputil.NewServerListener(ln, cfg, handler) // Addr is derived from ln
if err != nil {
    log.Fatal(err)
}

errChan := srv.Start() // serves on ln, never binds; StartTLS wraps it for HTTPS

The injected listener is owned by the Server from construction (ListenerAddr reports it before Start): net/http closes it when serving ends, so a NewServerListener server is single-serve — a restart after Shutdown returns the classified server.listener_consumed error. Bind a fresh listener and build a new Server to serve again.

Default timeouts match production recommendations:

  • ReadTimeout: 10s
  • ReadHeaderTimeout: 5s
  • WriteTimeout: 30s
  • IdleTimeout: 60s

Stdlib pass-through boundary: ServerConfig wraps the common timeouts and TLS settings; other http.Server knobs (for example Go 1.27's new MaxHeaderValueCount request-header cap) are not exposed — construct a plain http.Server when you need one.

Health Checks

Standard Kubernetes-compatible health handlers.

mux := http.NewServeMux()
httputil.RegisterHealth(mux)

// Registers:
//   GET /health
//   GET /health/live
//   GET /health/ready

Or use individual handlers:

mux.HandleFunc("GET /health", httputil.HealthHandler())

For dependency-based readiness (e.g., database connectivity):

mux.HandleFunc("GET /health/ready", httputil.ReadyHandlerWithProbe(db.Ping))

These handlers are the zero-dependency floor. For real probes — critical/non-critical classification, background caching, shutdown-aware readiness, aggregate and federation — pair httputil with go-health behind the same middleware; see Using httputil with go-health.

CSRF Protection

Double-submit cookie CSRF protection via justinas/nosurf with HTMX-aware helpers.

handler := httputil.CSRFMiddleware(httputil.CSRFConfig{})(mux)

For HTMX, pair with CSRFResponseHeaderMiddleware to automatically set the token in response headers:

handler := httputil.Chain(mux,
    httputil.CSRFMiddleware(httputil.CSRFConfig{}),
    httputil.CSRFResponseHeaderMiddleware,
)

Token helpers for templates: CSRFTokenFormField (hidden input), CSRFTokenHTMLMeta (meta tag), CSRFTokenHXHeaders (hx-headers attribute).

Call InvalidateCSRFCookie(w, cfg) on login/logout to rotate the token.

Origin attestation trust model. nosurf (verified at v1.2.0) skips Origin/Referer validation whenever a request carries a literal Sec-Fetch-Site: same-origin header. Browsers set that header truthfully and JavaScript cannot forge it (forbidden header name), so it is reliable against the classic cross-site attacker — but any non-browser client can send it manually. Two deliberate consequences:

  • A client-supplied attestation (or the plaintext-proxy bypass, SetPlaintextHTTPOrigin) 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 on plain HTTP — 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. The null origin is exempt (nosurf treats it as absent).

Migrating (behavior change in v1.0.0): a non-browser client that sent a forged Sec-Fetch-Site: same-origin alongside an Origin from a different host previously slipped past nosurf's origin validation (the attestation short-circuit) and only had to pass the token check. Such requests now get 403 with the csrf.origin_attestation_conflict error code before nosurf runs. Fix the client, not the middleware: send no Sec-Fetch-Site header at all (nosurf then applies normal Origin/Referer validation), or send a truthful attestation, or add the client's real origin to CSRFConfig.TrustedOrigins.

Plaintext-HTTP origin bypass: requests with no Origin/Referer/Sec-Fetch-Site header are auto-marked same-origin only when they arrive from loopback or TrustedProxies (or from everywhere with AllowPlaintextBypass, which logs a warning — it is insecure for internet-facing plain HTTP).

Server-Timing

W3C Server-Timing header with per-request sub-metrics. Lives in the server_timing sub-module (github.com/larsartmann/httputil/server_timing, package servertiming), which is MIT-licensed and has its own README.

import "github.com/larsartmann/httputil/server_timing"

handler := servertiming.ServerTimingMiddleware()(mux)

// In a handler:
stop := servertiming.MeasureServerTiming(r.Context(), "db")
result, err := db.Query(ctx)
stop()

Gate behind a predicate to expose only for admin/debug requests:

handler := servertiming.ServerTimingMiddlewareWhen(func(r *http.Request) bool {
    return r.URL.Query().Has("debug")
})(mux)
Endpoints Listing

A GET /endpoints listing of every route the server serves — JSON for API clients, an HTML table for browsers, picked by content negotiation on the Accept header. Lives in the endpoints sub-module (github.com/larsartmann/httputil/endpoints), which is MIT-licensed, stdlib-only with zero dependencies, and has its own README.

*http.ServeMux cannot enumerate the patterns registered on it, so the listing needs its own source of truth: every route registered through a Registry is mounted on the mux AND recorded in one declaration, so the listing cannot drift from what is actually served.

import "github.com/larsartmann/httputil/endpoints"

routes := endpoints.NewRegistry()
mux := http.NewServeMux()

// One declaration: mounts "GET /users/{id}" AND records it for the listing.
err := routes.HandleFunc(mux, "GET /users/{id}", getUser, "Fetch one user")
if err != nil {
    return err // wiring errors are values: nil mux, empty or duplicate pattern, non-UTF-8 summary
}

// Mount the listing itself — it lists itself too.
if err := endpoints.Register(mux, routes); err != nil {
    return err
}

Negotiation never 406s: an absent, unknown, or garbage Accept header serves JSON (json/v2); text/html or text/* serves the HTML table; q=0 excludes a representation and ties go to JSON. Both representations carry Vary: Accept + Cache-Control: no-store; methods other than GET/HEAD get 405 with Allow. The HTML is CSP-clean (no inline styles or scripts; every field escaped), so it composes with SecurityHeaders and Nonce. A route listing documents the attack surface — mount it deliberately if the service is internet-facing.

Rate Limiting

Token-bucket rate limiting per client key with O(log n) min-heap eviction and monitoring.

handler := httputil.KeyedRateLimiterMiddleware(httputil.DefaultKeyedRateLimiterConfig())(mux)

For monitoring active keys:

rl := httputil.NewKeyedRateLimiter(httputil.DefaultKeyedRateLimiterConfig())
fmt.Println(rl.ActiveKeys())
handler := rl.Middleware()(mux)

Rejected requests receive 429 Too Many Requests with a Retry-After header.

Behind a reverse proxy that appends to X-Forwarded-For (rather than stripping it), KeyExtractorFromClientIP() lets clients forge their rate-limit key. Use the trust-gated extractor instead — forwarded headers are honored only when the socket peer is inside the trusted CIDR set, and the list is walked right-to-left so a forged leftmost entry cannot outrank the honest one:

extractor, err := httputil.KeyExtractorFromTrustedClientIP([]string{"10.0.0.0/8"})
if err != nil {
	return err // invalid CIDR, fix the configuration
}

cfg := httputil.DefaultKeyedRateLimiterConfig()
cfg.KeyExtractor = extractor

ParseTrustedProxies(nil) builds the same value with the loopback-only default (local proxies and tests work with zero config); the returned TrustedProxySet also exposes ClientIP(r) and Contains(ip) for non-rate-limit consumers (vote guards, logging).

Content Language Negotiation

Negotiates the response language from Accept-Language (or a query param, cookie, or URL path prefix) against the app's supported tags, then stamps Content-Language and Vary: Accept-Language and exposes the served tag to handlers via the request context:

cfg := httputil.DefaultLanguageConfig()
cfg.SupportedTags = []string{"en", "de"}

handler := httputil.Language(cfg)(mux)

The default matcher falls back by primary subtag (de-AT serves de); supply a TagMatcher for full BCP 47 matching via golang.org/x/text. Extractors compose with LanguageExtractorChain — the first extractor producing a supported tag wins, so a cookie or path-prefix leg can outrank the header.

Ordering: Place Language outside CSRFMiddleware (the 403 page can localize, which needs the language context resolved) and inside CORS (CORS must stay outermost to answer preflights). Declared tag spellings are preserved — zh-Hans is served as zh-Hans; only comparisons are case-insensitive. ETag must also sit inside (after) Language: an ETag computed before language selection would let a cache serve language A's body to language B's conditional request.

handler := httputil.Chain(
    mux,
    httputil.CORS(httputil.DefaultCORSConfig()), // outermost: answers preflights
    httputil.CSRFMiddleware(httputil.CSRFConfig{}),
    httputil.Language(cfg),
    etagMiddleware, // innermost of the pair: hashes AFTER language selection
)
Error Classification

ResponseRecorder, compressWriter, and CSRFMiddleware errors are classified with behavioral families via go-error-family:

Source Error Code Family Retryable When
Write http.write_failed Transient Yes Underlying ResponseWriter.Write fails
Hijack http.hijack_unsupported Infrastructure No Underlying writer doesn't implement Hijacker
Hijack http.hijack_failed Transient Yes Underlying Hijack call fails
Push http.push_unsupported Infrastructure No Underlying writer doesn't implement http.Pusher (HTTP/1, httptest recorders)
Push http.push_failed Transient Yes Underlying Push call fails (stream reset, connection going away)
Compress http.compress_write_failed Transient Yes Compression writer Write/Close fails
CSRF csrf_invalid Rejection No CSRF token missing, malformed, or mismatched
CSRF csrf.origin_attestation_conflict Rejection No Sec-Fetch-Site: same-origin attestation contradicted by a cross-origin Origin header (forged attestation)
CSRF csrf_config Infrastructure No CSRF configuration invalid
CSRF csrf.max_age_negative Rejection No CSRFConfig.MaxAge is negative
CSRF csrf.trusted_origin_invalid Rejection No TrustedOrigins entry is not a usable scheme://host origin
CORS cors.methods_empty Rejection No CORSConfig.AllowedMethods is empty
Language language.* Rejection No LanguageConfig invalid (empty tags, invalid tag charset, unsupported default, nil extractor)
Compress compression.incompressible_prefix_invalid Rejection No IncompressibleTypes entry is empty or lacks a slash
Compress compression.absent_encoding_invalid Rejection No AbsentEncoding is not a known AbsentEncodingPolicy constant
Decompress decompression.encoding_unrecognized Rejection No Encodings entry other than gzip/deflate
Decompress decompression.encoding_duplicate Rejection No Same encoding listed twice
Ratelimit ratelimit.* Rejection No KeyedRateLimiterConfig invalid (zero limit/window, negative TTL, Burst above math.MaxInt32)

Call RegisterErrorClassifications() at startup to enable classification of stdlib HTTP errors and register error message templates.

Conditional-request outcomes have upstream classification guidance in go-error-family (README, "Conditional Requests"): 428 Precondition Required is a Rejection (an omitted precondition is incomplete input), 412 Precondition Failed is a Conflict via NewConflict(...).WithHTTPStatus(412) (a state clash — refresh and reapply), and 304 Not Modified is a success-path response, not an error — which is how the ETag middleware above produces it.

API

Function Signature Purpose
CORS func(CORSConfig) func(http.Handler) http.Handler CORS middleware factory
DefaultCORSConfig func() CORSConfig Permissive dev config (allows all origins)
ClientIP func(*http.Request) string Extract client IP from proxied request
ClientIPMiddleware func(http.Handler) http.Handler Store client IP in request context
ClientIPFromContext func(context.Context) string Retrieve stored client IP
WithClientIP func(context.Context, string) context.Context Store client IP in context
NewResponseRecorder func(http.ResponseWriter) *ResponseRecorder Wrap writer to capture status
Chain func(http.Handler, ...func(http.Handler) http.Handler) http.Handler Compose middleware
Compose func(...Middleware) Middleware Reusable middleware bundle (first = outermost)
SecurityHeaders func(SecurityHeadersConfig) func(http.Handler) http.Handler Security response headers
DefaultSecurityHeadersConfig func() SecurityHeadersConfig Sensible security defaults
RequestID func(RequestIDConfig) func(http.Handler) http.Handler Request ID propagation/generation
DefaultRequestIDConfig func() RequestIDConfig Default X-Request-ID config
RequestIDFromContext func(context.Context) string Retrieve stored request ID
Recovery func(*slog.Logger) func(http.Handler) http.Handler Panic recovery
RecoveryWithConfig func(RecoveryConfig) Middleware Panic recovery with an OnPanic observability hook
Timeout func(time.Duration) func(http.Handler) http.Handler Request deadline enforcement
Logging func(*slog.Logger) func(http.Handler) http.Handler Structured request logging
LoggingFromContext func(*slog.Logger, func(context.Context) *slog.Logger) Middleware Request logging with the logger resolved per request from context
MaxBodySize func(int64) func(http.Handler) http.Handler Request body size limit
Compression func(CompressionConfig) func(http.Handler) http.Handler Negotiated response compression
DefaultCompressionConfig func() CompressionConfig gzip/deflate defaults
DefaultWriterFactories func() map[string]WriterFactory Built-in gzip/deflate/identity factories
DefaultWriterFactoriesForLevel func(int) map[string]WriterFactory Built-in factories at a given compression level
GzipWriterFactory func(int) WriterFactory Stdlib gzip factory at a given level
DeflateWriterFactory func(int) WriterFactory Stdlib flate/raw-deflate factory
DefaultIncompressibleTypes func() []string Default content-type deny-list for compression
Decompression func(DecompressionConfig) func(http.Handler) http.Handler Request body decompression + bomb protection
DefaultDecompressionConfig func() DecompressionConfig gzip/deflate defaults
KeyedRateLimiterMiddleware func(KeyedRateLimiterConfig) func(http.Handler) http.Handler Per-key rate limiting with eviction
Language func(LanguageConfig) func(http.Handler) http.Handler Content-language negotiation (Content-Language + Vary stamping)
NewKeyedRateLimiter func(KeyedRateLimiterConfig) *KeyedRateLimiter Rate limiter with monitoring API
DefaultKeyedRateLimiterConfig func() KeyedRateLimiterConfig Default per-key rate limit config
KeyExtractorFromTrustedClientIP func([]string) (KeyExtractor, error) Client-IP keying gated by trusted-proxy CIDRs
ParseTrustedProxies func([]string) (TrustedProxySet, error) Parsed, immutable trusted-proxy set (.ClientIP/.Contains/.KeyExtractor)
CSRFMiddleware func(CSRFConfig) func(http.Handler) http.Handler CSRF protection middleware
CSRFResponseHeaderMiddleware func(http.Handler) http.Handler Auto-set CSRF token in response header
Nonce func(NonceConfig) func(http.Handler) http.Handler Per-request CSP nonce (context + optional CSP header)
DefaultNonceConfig func() NonceConfig Default CSP nonce config (20 bytes)
NonceAttr func(*http.Request) string Ready-to-use nonce="..." HTML attribute
ValidateCSRF func(*http.Request, CSRFConfig) (bool, *httptest.ResponseRecorder) Standalone CSRF validation
ServerTimingMiddleware func() func(http.Handler) http.Handler W3C Server-Timing middleware (server_timing module)
ServerTimingMiddlewareWhen func(func(*http.Request) bool) func(http.Handler) http.Handler Conditional Server-Timing (server_timing module)
endpoints.NewRegistry func() *endpoints.Registry Route registry for the /endpoints listing (endpoints module)
endpoints.Registry.Handle func(*http.ServeMux, string, http.Handler, string) error Mount a handler on the mux AND record its route
endpoints.Registry.HandleFunc func(*http.ServeMux, string, func(http.ResponseWriter, *http.Request), string) error Handle for a bare handler function
endpoints.Registry.Routes func() []endpoints.Route Registered routes, sorted defensive copy
endpoints.Registry.Handler func() http.Handler The content-negotiated listing handler (GET/HEAD, 405 otherwise)
endpoints.Register func(*http.ServeMux, *endpoints.Registry) error Mount the listing at DefaultPattern (GET /endpoints)
endpoints.Route struct { Method, Pattern, Summary string } One recorded route
endpoints.Response struct { Endpoints []endpoints.Route } Listing payload rendered as JSON or HTML
endpoints.DefaultPattern const "GET /endpoints" Pattern Register mounts by default
ParseUintQuery func(*http.Request, string) uint Parse uint from query param
Metrics func(MetricsConfig) func(http.Handler) http.Handler Request metrics recording
DefaultMetricsConfig func() MetricsConfig Default metrics config
NewMiddlewareStack func() *MiddlewareStack Named middleware stack builder
MiddlewareStack.Middleware() func() Middleware Nest the whole stack as one middleware
MiddlewareFunc.Then func(http.Handler) http.Handler Value-level chaining; nil wires a 500-stub handler
DetectCapabilities func(http.ResponseWriter) Capabilities Report Hijacker/Flusher/Pusher support
RegisterErrorClassifications func() Register stdlib error sentinels + templates
NewServer func(ServerConfig, http.Handler) (*Server, error) Configurable HTTP server with timeouts
NewServerListener func(net.Listener, ServerConfig, http.Handler) (*Server, error) Serve on a caller-bound listener (wrappers own the bind)
Server.ListenerAddr() func() (net.Addr, bool) Resolved listener address (:0 → real port); false when not listening
DefaultServerConfig func() ServerConfig Sensible server timeout defaults
RegisterHealth func(*http.ServeMux) Register /health + /live + /ready
HealthHandler func() http.HandlerFunc Simple {"status":"up"} handler
LiveHandler func() http.HandlerFunc Kubernetes liveness probe handler
ReadyHandler func() http.HandlerFunc Kubernetes readiness probe handler
ReadyHandlerWithProbe func(func() bool) http.HandlerFunc Readiness with dependency probe (200/503)
CORSConfig fields
Field Type Default Description
AllowedOrigins []string ["*"] Origins permitted in CORS responses (supports *.example.com)
AllowedMethods []string ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"] Allowed HTTP methods
AllowedHeaders []string ["Content-Type", "Authorization", "X-Request-ID"] Accepted request headers
ExposedHeaders []string [] Headers the browser may access
AllowCredentials bool false Whether to send credentials
MaxAge int 86400 Preflight cache duration in seconds
AllowAllOrigins bool true Respond with * for any origin
OptionsPassthrough bool false Forward OPTIONS to the next handler
DenyUnmatched bool true Withhold Allow-Origin for origins not in AllowedOrigins (secure by default)
AllowPrivateNetwork bool false Answer Chrome Local Network Access preflights (preflight responses only)

AllowPrivateNetwork is independent of origin matching: a denied-origin preflight (DenyUnmatched, no Allow-Origin) still carries the header — the browser already fails that response at the missing Allow-Origin, so no capability is granted. Note the MaxAge interplay: browsers cache preflight results (including the LNA grant) for Access-Control-Max-Age seconds, so lowering MaxAge also shortens how long an LNA allowance survives a config rollback.

ResponseRecorder methods
Method Returns Description
Status() int Captured status code (0 if WriteHeader not called)
WroteHeader() bool Whether WriteHeader was called
HeaderSnapshot() http.Header Isolated copy of response headers
WriteHeader(int) — Capture status and delegate
Write([]byte) (int, error) Write body, implicitly set 200
Flush() — Delegate if underlying writer supports http.Flusher
Hijack() (net.Conn, *bufio.ReadWriter, error) Delegate if underlying writer supports http.Hijacker
Push(string, *http.PushOptions) error Delegate an HTTP/2 server push; classified http.push_unsupported when the underlying writer lacks http.Pusher
CompressionConfig fields
Field Type Default Description
MinSize int 512 Minimum response body size before compression is attempted
Level int gzip.DefaultCompression Compression level used when WriterFactories is not supplied; applies to both gzip and deflate
WriterFactories map[string]WriterFactory gzip, deflate, identity Encoding-name → factory map; replace or extend
IncompressibleTypes []string DefaultIncompressibleTypes() Content-types to skip (nil = defaults, empty = compress all)
DecompressionConfig fields
Field Type Default Description
Encodings []string gzip, deflate Request body encodings to decompress; empty = both defaults
MaxDecompressionSize int64 16777216 Max decompressed body size in bytes to prevent zip bombs (16 MiB); 0 selects the 16 MiB default (no unlimited option)
KeyedRateLimiterConfig fields
Field Type Default Description
Limit uint 100 Maximum requests per Window per key
Window time.Duration 1m Time window for the limit
Burst uint 0 (= Limit) Maximum burst size (can exceed Limit)
KeyExtractor KeyExtractor KeyExtractorFromClientIP() Extracts the rate-limit key from the request
TTL time.Duration 10m How long idle entries are kept before eviction
MaxKeys uint 0 (unbounded) Caps tracked keys; oldest evicted at capacity
OnAllowed func(*http.Request) nil Callback when a request passes
OnRejected func(*http.Request, string) nil Callback when rejected (receives retryAfter)
RejectionHandler func(w, r, retryAfter) nil (429 + Retry-After) Custom handler for rejected requests
Now func() time.Time nil (= time.Now) Injected clock: controls refill, last-use stamps, and TTL eviction — tests advance time deterministically instead of sleeping
CSRFConfig fields
Field Type Default Description
CookieName string "csrf_token" Name of the CSRF cookie
HeaderName string "X-Csrf-Token" Request header containing the CSRF token (canonical MIME spelling; header names are case-insensitive on the wire)
FieldName string "csrf_token" Form field name for the CSRF token
MaxAge time.Duration 24h Cookie max age
Secure bool false Sets the Secure flag on the cookie (set true in production; with SameSite=None the constructor falls back to Secure=true)
SameSite http.SameSite SameSiteLaxMode SameSite attribute on the cookie
Domain string "" (host-only) Cookie domain
Path string "/" Cookie path
TrustedOrigins []string nil Origins allowed for cross-domain CSRF (each must be a scheme://host origin; parsing is all-or-nothing — one bad entry means no trusted origins)
TrustedProxies []string nil IP/CIDR of reverse proxies that may strip origin headers
AllowPlaintextBypass bool false Allow plaintext-HTTP origin bypass for all non-TLS requests (insecure)
BootLogUntrustedForwardedProto bool false Opt-in boot warning when TrustedProxies is empty (XFP trust path silently inactive behind a TLS-terminating proxy)
AllowInsecureSameSiteNone bool false Keep SameSite=None without Secure instead of the Secure=true fallback (legacy clients only; browsers refuse to store the cookie)
ErrorHandler ErrorHandler nil (403 + body) Custom handler for CSRF validation failures

When SameSite is None and Secure is false, CSRFMiddleware (and InvalidateCSRFCookie) fall back to Secure=true at construction instead of honoring the combination verbatim: rfc6265bis §5.7 makes such cookies unstorable in current browsers, so the previously-honored misconfiguration meant every state-changing browser request failed CSRF validation. The fallback keeps the None intent (cross-site cookies still work on HTTPS deployments), logs csrf_samesite_insecure, and is skipped verbatim with AllowInsecureSameSiteNone: true for legacy-client deployments. ConfigureNosurfHandler applies no fallback — it is the verbatim low-level configurator.

MetricsConfig fields
Field Type Default Description
Recorder MetricsRecorder nil Receives one observation per request (required)
PathFunc func(*http.Request) string nil (r.URL.Path) Extracts the path to record from the request
SecurityHeadersConfig fields
Field Type Default Description
ContentTypeNosniff bool true Set X-Content-Type-Options: nosniff
FrameOptions string "DENY" X-Frame-Options value (empty = header omitted)
StrictTransportSecurity string "" Strict-Transport-Security value (empty = omitted)
ReferrerPolicy string "strict-origin-when-cross-origin" Referrer-Policy value (empty = omitted)
ContentSecurityPolicy string "" Content-Security-Policy value (empty = omitted)
RequestIDConfig fields
Field Type Default Description
ResponseHeader string "X-Request-ID" Response header to set with the resolved request ID
GenerateID func() string Time-ordered hex ID generator invoked when no incoming header is present
IncomingHeader string "X-Request-ID" Incoming request header to read the upstream ID from
ServerConfig fields
Field Type Default Description
Addr string ":8080" Listen address
ReadTimeout time.Duration 10s Maximum duration for reading the entire request
ReadHeaderTimeout time.Duration 5s Maximum duration for reading request headers
WriteTimeout time.Duration 30s Maximum duration before timing out writes
IdleTimeout time.Duration 60s Maximum time to wait for the next request on a connection

Handling errors from httputil

Every error this package produces is classified via go-error-family: it carries a machine-readable code (cors.max_age_negative), a behavioral family (Rejection, Transient, ...), and factual context (the offending field value). Three questions cover every consumer need:

// 1. Which component failed? Match by domain (the code's prefix).
if httputil.InDomain(err, httputil.Domain("cors")) {
    // a CORS misconfiguration, not a network failure
}

// Route a CSRF rejection by its exact code — e.g. a 403 carrying
// csrf.origin_attestation_conflict means a client sent a forged
// Sec-Fetch-Site: same-origin attestation next to a cross-origin Origin.
// That is forged client input (Rejection family): fix or block the client,
// never retry.
if httputil.InDomain(err, httputil.Domain("csrf")) {
    if coded, ok := errors.AsType[errorfamily.Coded](err); ok &&
        coded.ErrorCode() == "csrf.origin_attestation_conflict" {
        log.Printf("forged CSRF attestation from %s", r.RemoteAddr)
    }
}

// 2. What is the exact failure? Read the code via the Coded interface.
if coded, ok := errors.AsType[errorfamily.Coded](err); ok {
    log.Printf("code=%s", coded.ErrorCode()) // e.g. "server.timeout_ordering"
}

// 3. Should I retry? Ask the family.
if errorfamily.IsRetryable(err) { backoffAndRetry(err) }

Conventions:

  • Codes are hierarchical: domain.specific_failure (e.g. compression.qvalue_too_large). Config-validation codes are Rejection (fix the config, never retry); runtime write/hijack failures are Transient; shutdown and pool-contract violations are Infrastructure.
  • Sentinels still work: errors.Is(err, ErrCSRFInvalid) matches by code and family, including through wrapped chains.
  • Message templates: call httputil.RegisterErrorClassifications() once at startup to register user-facing what/why/fix/escape templates for every code; retrieve them with errorfamily.TemplateForCode.
  • Constructor logging: middleware constructors log invalid configs (validate-and-log, not abort) with structured code, family, and domain fields, so log pipelines can route misconfigurations without parsing messages.

Design

  • Stdlib-first — all middleware uses func(http.Handler) http.Handler, compatible with any Go HTTP framework
  • Round-trip fuzz invariants — every response-transforming middleware ships a decode-and-compare fuzz invariant (e.g. FuzzCompression gunzips every negotiated-gzip response and compares bytes); the invariant caught a real exact-fill duplication bug that 96.9% line coverage had missed. The nightly fuzz workflow runs all 30 of the repo's fuzz targets at 5 minutes each in CI.
  • Classified errors — ResponseRecorder errors carry behavioral families (Transient, Infrastructure) and structured context via go-error-family for observability and retry logic
  • Minimal dependencies — go-error-family (same author, zero transitive deps), go-etag (same author, ETag conditional requests), golang.org/x/time (canonical Go rate-limit extension), and justinas/nosurf (CSRF protection).
Middleware Ordering

Chain applies middleware in reverse declaration order so the first argument is outermost:

handler := Chain(mux,
    Logging(logger),          // outermost — logs first, sees final status
    Recovery(logger),         // catches panics before they reach Logging
    Timeout(30*time.Second),  // enforces deadline
    RequestID(DefaultRequestIDConfig()),
    SecurityHeaders(DefaultSecurityHeadersConfig()),
    Nonce(DefaultNonceConfig()), // after SecurityHeaders so nonce CSP wins
    CORS(DefaultCORSConfig()),
)

Ordering at a glance (outermost first):

flowchart LR
    A[Logging] --> B[Recovery] --> C[Timeout] --> D[RequestID] --> E[SecurityHeaders]
    E --> F[Nonce] --> G[CORS] --> H[Decompression] --> I[MaxBodySize] --> J[Compression] --> K[ETag] --> M[Mux]

Decompression should be placed outer so downstream middleware (e.g., MaxBodySize) sees the decompressed body size:

// Decompression outer: handlers see decompressed bytes.
// MaxBodySize limits the decompressed size, not the compressed size.
handler := Chain(mux, Decompression(cfg), MaxBodySize(1<<20))

ETag must be placed inside (after) Compression so it hashes the uncompressed body. If placed before Compression, the ETag would be computed over the compressed bytes — different content encodings on the wire would yield different ETags for the same logical resource, defeating conditional caching:

// Compression outer, ETag inner: ETag hashes the body the handler produced,
// not the bytes that left over the wire. All clients see the same ETag value
// regardless of which Accept-Encoding they negotiated.
handler := Chain(mux, Compression(cfg), etag.New(etag.DefaultETagConfig()))
Compression Extensibility

The default configuration supports gzip and deflate. Brotli, zstd, and other modern encodings are supported via the WriterFactory plugin interface without adding dependencies to the core library.

cfg := httputil.DefaultCompressionConfig()
cfg.WriterFactories["zstd"] = func(dst io.Writer) (io.WriteCloser, error) {
    return zstd.NewWriter(dst)
}
handler := httputil.Compression(cfg)(mux)

This keeps the core package dependency-free while allowing you to plug in any encoder that implements io.WriteCloser.

For a complete guide including pool reuse and brotli/zstd patterns, see the compression extensibility example.

Framework Integration

httputil composes cleanly with declarative API frameworks like Huma, which generates OpenAPI 3.1 + JSON Schema from Go types but deliberately ships no middleware. Both target the same Go 1.22+ http.ServeMux via the humago adapter — no third-party router required:

router := http.NewServeMux()
api := humago.New(router, huma.DefaultConfig("My API", "1.0.0"))
huma.Get(api, "/things/{id}", getThing) // huma: types, validation, OpenAPI

handler := httputil.Chain(router, // httputil: compression, security, logging
    httputil.Recovery(slog.Default()),
    httputil.Logging(slog.Default()),
    httputil.Compression(httputil.DefaultCompressionConfig()),
    httputil.SecurityHeaders(httputil.DefaultSecurityHeadersConfig()),
    httputil.CORS(httputil.DefaultCORSConfig()),
)

See the full integration example and the detailed comparison.

For dependency injection and graceful lifecycle management, pair httputil with samber/do — httputil.Server.Shutdown(context.Context) error satisfies do.ShutdownerWithContextAndError structurally, so the container discovers and shuts down the HTTP server automatically. See the composition-root example.

For observability, see the Prometheus MetricsRecorder example. To build a secure middleware baseline once and apply it to many handlers (or nest whole stacks), see Composing Middleware Bundles.

Quality Gates

This project maintains strict quality standards enforced in CI:

Gate Command Status
Tests go test -race -count=1 ./... Passing
Race stress go test -race -count=10 ./... Passing
Coverage go test -coverprofile=coverage.out ./... 98.7% httputil / 98.4% httpspec (threshold: 95%)
Lint golangci-lint run (~70 linters) 0 issues
Vet go vet ./... Clean
Vulnerabilities govulncheck ./... None found
Nix flake nix flake check All checks passed
Module integrity go mod verify All modules verified

Development

go test ./...               # Run tests
go test -race ./...         # Race detection (REQUIRED for t.Parallel())
go test -race -count=10 ./...  # Stress race detection
go vet ./...                # Vet
go test -bench=. ./...      # Benchmarks
golangci-lint run           # Lint (~70 linters)
golangci-lint fmt           # Format (gofumpt + golines@120 + gci)
govulncheck ./...           # Vulnerability scan
nix flake check             # Nix flake validation

License

MIT — see LICENSE. The server_timing and endpoints sub-modules are MIT-licensed as well, each with its own LICENSE/LICENSE and README/README.

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

Examples

Constants

View Source
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"
)
View Source
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.

View Source
const (
	DefaultRateLimit  = 100
	DefaultRateWindow = time.Minute
	DefaultRateTTL    = 10 * time.Minute
)

Keyed rate limiter defaults.

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

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

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

View Source
var ErrCSRFConfig = errorfamily.NewInfrastructure(
	string(codeCSRFConfig),
	"invalid CSRF configuration",
)

ErrCSRFConfig is returned when the CSRF configuration is invalid or insecure.

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

func CSRFResponseHeaderMiddleware(next http.Handler) http.Handler

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

func CSRFTestToken(middleware func(http.Handler) http.Handler) (string, *http.Cookie)

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

func CSRFTokenFormField(r *http.Request) string

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

func CSRFTokenFromContext(ctx context.Context) string

CSRFTokenFromContext retrieves the CSRF token stored by CSRFMiddleware. Returns an empty string if no token is present.

func CSRFTokenFromRequest

func CSRFTokenFromRequest(r *http.Request) string

CSRFTokenFromRequest extracts the CSRF token from either the nosurf request context or the httputil context. Returns "" if no token is present.

func CSRFTokenHTMLMeta

func CSRFTokenHTMLMeta(r *http.Request) string

CSRFTokenHTMLMeta returns an HTML meta tag containing the CSRF token.

func CSRFTokenHXHeaders

func CSRFTokenHXHeaders(r *http.Request) string

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

func ClientIP(req *http.Request) string

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

func ClientIPFromContext(ctx context.Context) string

ClientIPFromContext retrieves a previously stored client IP from the context. Returns empty string if no IP was stored.

func ClientIPMiddleware

func ClientIPMiddleware(next http.Handler) http.Handler

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

func InDomain(err error, domain Domain) bool

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

func LanguageFromContext(ctx context.Context) string

LanguageFromContext retrieves the negotiated language tag. Returns an empty string when no language was stored.

func LanguageFromRequest added in v1.6.0

func LanguageFromRequest(r *http.Request) string

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

func NonceAttr(r *http.Request) string

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

func NonceFromContext(ctx context.Context) string

NonceFromContext retrieves the nonce from the context. Returns an empty string if no nonce was stored.

func NonceFromRequest

func NonceFromRequest(r *http.Request) string

NonceFromRequest retrieves the nonce from the request context. Returns an empty string if no nonce was stored. Convenience wrapper around NonceFromContext.

func ParseUintQuery

func ParseUintQuery(r *http.Request, key string) uint

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

func ProductionCSPWithNonce(nonce string) string

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

func RecommendedCSPWithNonce(nonce string) string

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

func RegisterHealth(mux *http.ServeMux)

RegisterHealth registers /health, /health/live, and /health/ready on the given *http.ServeMux using the default handlers.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

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

func WithCSRFToken(ctx context.Context, token string) context.Context

WithCSRFToken stores a CSRF token in the context.

func WithClientIP

func WithClientIP(parent context.Context, ip string) context.Context

WithClientIP stores the extracted client IP in the request context. Retrieve it later with ClientIPFromContext.

func WithLanguage added in v1.6.0

func WithLanguage(parent context.Context, tag string) context.Context

WithLanguage stores the negotiated language tag in the context. Retrieve it with LanguageFromContext or LanguageFromRequest.

func WithNonce

func WithNonce(parent context.Context, nonce string) context.Context

WithNonce stores the nonce in the request context. Retrieve it with NonceFromContext or NonceFromRequest.

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

func CodeOf(err error) (Code, bool)

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

func (c Code) Domain() 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

func DomainOf(err error) (Domain, bool)

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

type KeyExtractor func(r *http.Request) string

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

type LanguageExtractor func(r *http.Request) (tags []string, ok bool)

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

type Middleware = func(http.Handler) http.Handler

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

type MiddlewareFunc func(http.Handler) http.Handler

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

func (srv *Server) Addr() string

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

func (srv *Server) ListenerAddr() (net.Addr, bool)

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

func (srv *Server) Shutdown(ctx context.Context) error

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

func (srv *Server) Start() <-chan error

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

func (srv *Server) StartTLS(certFile, keyFile string) <-chan error

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

type TagMatcher func(tag string) (supported string, ok bool)

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.).

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
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.

Jump to

Keyboard shortcuts

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