webhttp

package module
v4.1.0-dev.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

README

webhttp

Go Reference Go version Mutation

webhttp hardens your Go net/http server with access logging, security headers, a client IP that cannot be spoofed and graceful shutdown.

It replaces the middleware, proxy-header parsing and shutdown sequence you would otherwise write around http.ServeMux, and every piece stays a plain http.Handler. It ships no router, and your app keeps its own routes and error codes. It uses only the standard library, needs Go 1.27.1 or later and is licensed under Apache-2.0.

Why use it

webhttp is built for a Go service on http.ServeMux that faces a browser or sits behind a proxy.

  • ResolveClient and ClientIP read X-Forwarded-For only from a proxy you trust, so a client cannot fake its address. ResolveClient also reports whether an unlisted proxy sent a forwarding header.
  • A Host allowlist answers 403 to a Host you did not list, which stops DNS rebinding attacks.
  • The access log writes log/slog lines and caps the path at 512 bytes and the method at 24. Metric labels stay within ten method values and your registered routes.
  • NewServer leaves the write timeout off, so SSE and WebSocket streams stay open. Run drains in-flight requests within a 5-second grace period by default.
  • StaticHandler serves an embed.FS with content-hash ETags and gzip computed once at startup.

Consider chi if you want a router with route groups, inline middleware and sub-router mounting. Consider golang.org/x/time/rate if you need a token bucket per client or one that waits instead of refusing.

Install

go get github.com/cplieger/webhttp/v4@latest

Usage

package main

import (
	"context"
	"log/slog"
	"net"
	"net/http"
	"os/signal"
	"syscall"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	ready := &webhttp.Ready{}

	mux := http.NewServeMux()
	mux.Handle("GET /readyz", webhttp.ReadinessHandler(ready))
	mux.HandleFunc("POST /things", func(w http.ResponseWriter, r *http.Request) {
		var body struct {
			Name string `json:"name"`
		}
		if !webhttp.DecodeBody(w, r, &body, "invalid thing payload") {
			return
		}
		webhttp.WriteJSONStatus(w, http.StatusCreated, body)
	})

	// The first middleware listed is the outermost. Logging sits outside
	// Recoverer so a recovered panic is logged as its 500.
	handler := webhttp.Chain(mux,
		webhttp.Logging(
			webhttp.WithSkipPaths("/events"), // a long-lived stream
			webhttp.WithRecordRouteMetric(func(m webhttp.RequestMetric) {
				// m.Method and m.Path are bounded labels. Feed your metrics here.
			}),
		),
		webhttp.Recoverer(),
		webhttp.SecurityHeaders(),
	)

	// Only header reads and idle connections time out, so streams stay open.
	srv := webhttp.NewServer(handler, webhttp.WithSlogErrorLog(slog.LevelError))

	// Bind first, so a port already in use fails here.
	ln, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	ready.Set(true)
	if err := webhttp.Run(ctx, srv, ln, func(context.Context) {
		// application teardown after the drain
	}, webhttp.WithPreDrain(func(context.Context) { ready.Set(false) })); err != nil {
		panic(err)
	}
}

A service that browsers reach should also refuse unknown Host names. Build a HostPolicy with ParseHostList and put its Middleware() in the chain ahead of any cross-origin or CSRF check. An API that only machines call can skip it. The examples on pkg.go.dev run under go test, which keeps them true.

API

  • Middleware: Chain, Recoverer, SecurityHeaders, Gzip, Logging, RouteTimeout, RateLimiter with its SessionCreateRateLimit and FailedAuthRateLimit presets, NoStore.
  • Logging and metrics: RequestLogger and its options, request-id helpers, RouteMetricLabels, StatusRecorder.
  • Trust checks: ClientIP, ResolveClient, ParseCIDRs, ParseHostList and HostPolicy, CanonicalHost, LoopbackOnly, ClassifyBind, NewStaticTokenVerifier.
  • Requests and responses: WriteJSON, WriteError and ErrorCode, DecodeBody, DecodeJSONInto, LimitBody, RequireMethod, MethodNotAllowed, CanonicalRequestPath.
  • Static files: StaticHandler, InlineScriptHashes, InlineStyleHashes.
  • Server: NewServer, Run and its options, Ready and ReadinessHandler, AwaitDone, CausedByCancellation.

The full reference is on pkg.go.dev.

Middleware order and safety rules

Chain(h, A, B, C) builds A(B(C(h))), so the first entry sees the request first. Any func(http.Handler) http.Handler fits. Put Recoverer inside Logging and Gzip inside Recoverer, as in Chain(mux, Logging(), Recoverer(), Gzip()). Otherwise the access log can show 200 where the client got 500, or a panic can lose its 500.

Place a HostPolicy before any cross-origin or CSRF check. In a DNS rebinding attack, the page's Origin and the request's Host both name the attacker's domain, so a cross-origin check passes it and only the Host allowlist refuses it. Place NoStore innermost, so a handler that sets its own Cache-Control still wins.

SecurityHeaders always sends X-Content-Type-Options: nosniff, and by default X-Frame-Options: DENY and Referrer-Policy: strict-origin-when-cross-origin. It builds no Content-Security-Policy and sends no HSTS until you pass WithCSP or WithHSTS. Enable HSTS only for a service reached over HTTPS alone. A browser that has seen the header refuses plain-HTTP and untrusted-certificate connections to the host for the whole max-age.

RouteTimeout buffers the whole response, so never wrap a streaming or hijacking handler with it. Middleware has each option and default.

Behind a proxy, ClientIP is safe only when the trusted set holds every proxy hop. It reads at most 64 entries of each forwarding header and treats a longer header as invalid. LoopbackOnly is not authentication, because a proxy on the same loopback interface that removes every forwarding header passes it. An empty NewStaticTokenVerifier secret denies every value. When a page carries inline scripts, treat an empty InlineScriptHashes result as a startup error and never fall back to 'unsafe-inline'.

Graceful shutdown

When ctx is cancelled, Run runs the WithPreDrain hook, then srv.Shutdown drains in-flight requests, then onShutdown runs. All three share one grace budget, 5 seconds unless you set WithShutdownGrace. Use the pre-drain hook to mark the instance unready or close long-lived streams, so they do not hold the drain open.

When Serve returns before ctx is cancelled, for example because the listener failed, neither hook runs. Pass WithServeExit to run your teardown in that case too. A Run error caused by the grace running out wraps ErrShutdownGraceExpired. Server, readiness and shutdown has the full sequence.

  • httpx makes the requests your service sends out survive flaky servers. webhttp handles the requests coming in.
  • health is the container liveness probe for a Docker HEALTHCHECK. ReadinessHandler answers a load balancer instead.
  • auth handles user logins and sessions. NewStaticTokenVerifier checks one configured machine credential.

Documentation

Credits

RateLimiter's refill and Retry-After math follows golang.org/x/time/rate, including its guard against a clock that moves backwards.

Contributing

Issues and pull requests are welcome. See CONTRIBUTING.md.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package webhttp is server-side HTTP plumbing on top of net/http: request-id and bounded access logging (RequestLogger, Logging), a transparent StatusRecorder, composable middleware (Chain, Recoverer, SecurityHeaders, Gzip, RouteTimeout, RateLimiter and its presets, NoStore), a spoof-aware ClientIP and ResolveClient, a Host allowlist against DNS rebinding (HostPolicy, CanonicalHost), an embedded StaticHandler, JSON envelope helpers (WriteJSON, WriteError), request preludes (LimitBody, RequireMethod, DecodeBody), a constant-time NewStaticTokenVerifier, ClassifyBind, a readiness gate, and a graceful server (NewServer, Run).

Middleware is func(http.Handler) http.Handler and Chain lists the outermost first, so Chain(mux, Logging(), Recoverer(), SecurityHeaders()) logs a recovered panic as its 500, and a stdlib middleware such as http.CrossOriginProtection's Handler composes with no adapter. The package depends on nothing beyond the standard library.

Index

Examples

Constants

View Source
const HeaderRequestID = "X-Request-ID"

HeaderRequestID is the canonical request-id header. RequestLogger reads it from the inbound request and echoes it on the response.

View Source
const MaxJSONBody int64 = 1 << 20

MaxJSONBody is the default maximum JSON request-body size (1 MiB) applied by DecodeBody and DecodeBodyOptional.

Variables

View Source
var (
	ErrHSTSPreloadWithoutSubdomains = errors.New("webhttp: HSTS preload requires IncludeSubdomains")
	ErrHSTSPreloadMaxAgeTooShort    = errors.New("webhttp: HSTS preload requires MaxAge of at least one year")
)

The two relational rules an HSTS value carries, both of them preload submission criteria the browser preload list enforces (hstspreload.org): preload is meaningless without includeSubDomains, and a preload submission needs a max-age of at least one year. Both are policed, and for the same reason: a policy asking for preload while failing a submission criterion is a policy that will never be preloaded, which is silently not what the caller asked for. Without Preload set, MaxAge is unconstrained — a short max-age is a valid working policy, it just cannot be preloaded.

View Source
var ErrShutdownGraceExpired = errors.New("webhttp: shutdown grace period expired")

ErrShutdownGraceExpired marks a Run return whose origin was the shutdown grace period running out, so a caller can tell WHICH DeadlineExceeded it is holding.

Run's error is one value with two possible origins: a serve error carrying a deadline of the caller's own making, or the graceful sequence outliving the single shutdown grace. Both can satisfy errors.Is(err, context.DeadlineExceeded), and a caller that assumes the second is asserting something the value alone cannot prove. A grace-expiry return is wrapped so both hold:

errors.Is(err, webhttp.ErrShutdownGraceExpired) // the origin: the grace ran out
errors.Is(err, context.DeadlineExceeded)        // still true, unchanged

The diagnosis itself stays the caller's: naming the grace constant to raise, deciding the log level, and choosing the exit code are app policy.

View Source
var ErrTrailingData = errors.New("webhttp: unexpected data after JSON value")

ErrTrailingData is returned by DecodeJSONInto when the body holds more than a single JSON value (data follows the first decoded value). Callers that map decode errors to a status treat it like any other malformed-body error (400).

Functions

func AwaitDone

func AwaitDone(ctx context.Context, done <-chan struct{}) bool

AwaitDone blocks until done is closed or ctx expires, and reports whether done closed in time. It is the bounded WAIT a teardown needs, not the teardown itself: shutdown teardown bodies stay app-owned, and so does every policy around the result — what to log, at which level, whether to name the grace constant, whether to count it.

It deliberately creates NO timeout of its own and logs nothing. Run hands onShutdown a context carrying whatever remains of the ONE shutdown grace after the pre-drain phase and the HTTP drain have spent their share, so a fresh deadline invented here would hand the teardown a budget the shutdown sequence does not actually have.

The post-expiry recheck is the reason this is worth sharing. A drain that consumed the whole grace hands the teardown an ALREADY-EXPIRED context, and a select whose cases are both ready picks pseudo-randomly — so the naive two-case select reports a goroutine that DID finish as still running a fraction of the time, turning a clean drain into a spurious warning. After ctx fires, AwaitDone re-checks done and only then reports false.

A nil done channel never becomes ready, so the wait is then bounded by ctx alone.

func CanonicalHost

func CanonicalHost(hostport string) string

CanonicalHost parses an HTTP Host header value (or a configured allowlist entry) into its canonical host for exact comparison, returning "" when the value is not a well-formed authority. Accepted shapes, per the RFC 3986 authority grammar:

  • a DNS name of ASCII labels (letters, digits, hyphens, and underscores — Docker Compose service names carry underscores — 63 bytes max per label), optionally ending in one FQDN dot, optionally followed by one ":port" (digits, at most 65535)
  • an IPv4 literal, with the same optional trailing dot and :port
  • a bare IPv6 literal (no port: an unbracketed colon-bearing value can only be an address, never host:port)
  • a bracketed IPv6 literal "[...]", optionally followed by ":port"

The canonical form is lowercase with no port, no brackets, and no trailing dot; IP literals are rendered through net.ParseIP so textually different spellings of one address (::1 vs 0:0:0:0:0:0:0:1, [::ffff:192.0.2.1] vs 192.0.2.1) compare equal. The function is idempotent: CanonicalHost(CanonicalHost(x)) == CanonicalHost(x).

Lowercasing is ASCII-ONLY (lowerASCIIString), not strings.ToLower, and that is load-bearing rather than an optimization. Unicode simple case mapping lowercases two already-assigned runes INTO ASCII — U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE to "i" and U+212A KELVIN SIGN to "k" — so under strings.ToLower a Host of "\u212Aibana.example" canonicalized to "kibana.example" and an allowlist holding the ASCII name admitted it, from any peer. That is the same widening the reject-never-repair rule below exists to prevent, arriving through the case fold instead of the grammar. With an ASCII fold every non-ASCII byte survives the fold and validHostname then refuses it, which is what makes the byte-exact claim above true.

Everything else returns "": stray or unmatched brackets, a bracketed non-IPv6 ("[allowed.example]" — brackets are IPv6-only syntax), a non-numeric, out-of-range, or empty port, a second port, more than one trailing dot, an empty label, a non-ASCII name (configure the Punycode A-label, "xn--...", instead — matching is byte-exact and no IDN mapping is performed), and an all-numeric dotted name that net.ParseIP rejects ("127.0.0.001", "0177.0.0.1" — HTTP clients disagree on leading-zero and octal IPv4 forms, so no single textual key can match them safely).

The sibling ssrf library carries its own numeric-IPv4 heuristic (looksLikeNumericIPv4) with a deliberately DIFFERENT reject set: ssrf feeds a resolver, so it must also reject dotted-hex forms like "0x7f.0.0.1" that this exact-match key safely accepts (the "x" makes the label a plain DNS label, matchable only if explicitly allowlisted). The two must NOT be unified — see that function's doc for the outbound rationale.

Malformed input is REJECTED, never repaired. Deleting the offending syntax instead (stripping stray brackets, truncating at a bad port) would let distinct wire values collapse onto an allowlisted key — "[allowed.example]", "allowed[.]example", and "allowed.example:garbage:443" would all admit as "allowed.example" — silently widening an exact-match allowlist.

No name resolution is performed. Resolving a hostname to compare against the request would reopen the very DNS-rebinding race a host allowlist exists to close (the attacker controls what the name resolves to), so matching is purely textual on the canonicalized Host.

func CanonicalRequestPath

func CanonicalRequestPath(p string) (clean string, canonical bool)

CanonicalRequestPath returns the request path http.ServeMux will route p as, and reports whether p already IS that path.

clean is the same computation net/http performs on every non-CONNECT request before it selects a pattern: path.Clean, with a non-root trailing slash put back (see cleanPath in net/http's server.go). canonical is clean == p, so it answers "will the mux route this spelling, or rewrite it first?".

Why a library surface exists for this

When the cleaned path differs, ServeMux answers 307 with a Location instead of calling any handler, and no registered pattern can intercept it — the canonicalization runs BEFORE pattern selection. For a browser that is invisible and harmless. For the machine senders these services actually have it is neither: a 307 is a SUCCESS status to a client that does not follow redirects (`curl -fsS` without -L is the documented sender for several of them), so such a caller exits 0 having never reached the handler. Nothing was recorded, no job ran, and nothing anywhere says the URL was malformed — the failure surfaces a deadline later as silence, if at all. A route whose whole purpose is a side effect wants to refuse the non-canonical spelling itself rather than let the redirect answer for it.

Which value to pass, and what that means

ServeMux cleans r.URL.EscapedPath(), so passing that is what reproduces its cleaning decision exactly. Passing the DECODED r.URL.Path instead makes the verdict strictly WIDER: %2e%2e decodes to .., so an encoded dot segment reports non-canonical here while ServeMux draws no redirect for it. That is a deliberate choice available to the caller, not a defect — the decoded path is the one the sender believed it was addressing — but it is a choice, so pick the value on purpose.

What canonical does NOT claim

It is the verdict of the cleaning step alone, not "ServeMux will not redirect this request". Two things are outside it, both by construction:

  • The trailing-slash redirect. When a subtree pattern "/tree/" is registered and the request is the already-canonical "/tree", ServeMux redirects to "/tree/". That depends on the route table, not on the path's spelling, so a pure function over p cannot see it.
  • CONNECT. net/http does not canonicalize a CONNECT request's path at all, so the cleaning redirect never applies to one.

Edge inputs

An empty p returns "/" and false, and a p with no leading slash is rooted before cleaning ("beat/api" cleans to "/beat/api"), so it can never equal p and always reports false. Both mirror net/http's own rooting, and neither reaches a handler from net/http on a normal request (an origin-form request target starts with "/", and an empty one is rejected before routing), so they are the answers for a caller passing a value from somewhere else.

What stays the caller's

Everything but the verdict: which routes the check applies to, whether a non-canonical spelling is refused or merely logged, the refusal's status and body, and any metric that counts the class. This is a pure function over a string and nothing else.

func CausedByCancellation

func CausedByCancellation(ctx context.Context, err error) bool

CausedByCancellation reports whether err is the observable form of THIS context's cancellation, so a boundary can tell a routine stop apart from a fault that merely happened at the same moment.

It PROVES the match rather than assuming it. A cancelled context alone is not evidence: a listener bind that genuinely failed while a signal was arriving must still read as a bind failure, not as a clean stop — the classification mistake this predicate exists to prevent. So err must carry either the stable ctx.Err() or the cancellation cause.

Matching context.Cause(ctx) as well as ctx.Err() is what makes it usable at a net/http boundary: a cause passed to context.WithCancelCause need not wrap context.Canceled, and net/http reports a cancelled operation as the cause verbatim, so a ctx.Err()-only check misses it. A nil ctx, a nil err, or a context that is not cancelled all report false.

What to DO with a true answer stays the caller's policy — the log level, the message, the exit code, and whether the operation is retried are none of the library's business.

func Chain

func Chain(h http.Handler, mw ...Middleware) http.Handler

Chain wraps h with the given middlewares and returns the composed handler. The FIRST middleware listed becomes the OUTERMOST wrapper: it is the first to see the request on the way in and the last to touch the response on the way out. The LAST middleware listed sits closest to h.

So Chain(h, A, B, C) is equivalent to A(B(C(h))): a request flows A -> B -> C -> h and the response unwinds h -> C -> B -> A. List middlewares in the order you want them to execute; a typical stack puts logging outermost so it observes the final status, then a panic recoverer, then app concerns:

handler := webhttp.Chain(mux,
	webhttp.Logging(),         // outermost: logs every request
	webhttp.Recoverer(),       // catches panics from everything below it
	webhttp.SecurityHeaders(), // sets headers before the app runs
)

A nil middleware in the list is skipped, so callers can include entries conditionally.

func ClientIP

func ClientIP(r *http.Request, trusted ...netip.Prefix) string

ClientIP returns ResolveClient's IP as text, for a log line or a rate-limit key; a RemoteAddr that is not an IP address gives "invalid IP", the zero Addr's text.

func DecodeBody

func DecodeBody(w http.ResponseWriter, r *http.Request, v any, errMsg string) bool

DecodeBody limits the body to MaxJSONBody and decodes exactly one JSON value into v. The decoded value must be the entire body: trailing data or a second JSON value is rejected. On any decode failure it writes a 400 error response (code "bad_request") carrying errMsg and returns false; on success it returns true. It is DecodeJSONInto at the default cap with a coded-400 response — see DecodeJSONInto for the mechanism and the app-taxonomy escape hatch.

func DecodeBodyOptional

func DecodeBodyOptional(w http.ResponseWriter, r *http.Request, v any)

DecodeBodyOptional limits the body to MaxJSONBody and attempts a JSON decode into v, discarding every error. It does NOT reliably leave v at its zero value: trailing data ({"a":1} junk) leaves the LEADING value in v where DecodeBody rejects it, and an oversize body is indistinguishable from an absent one — its *http.MaxBytesError is discarded too, so the handler answers 200 from a zero value (or from one that preceded the excess) while net/http closes the connection. DecodeJSONInto separates all five outcomes, with errors.Is(err, io.EOF) marking the absent body.

func DecodeJSONInto

func DecodeJSONInto(w http.ResponseWriter, r *http.Request, v any, maxBytes int64) error

DecodeJSONInto caps the request body at maxBytes (via LimitBody) and decodes exactly one JSON value into v, rejecting trailing data (a second value or any bytes past the first are an error). It returns the decode error and writes NOTHING to w — so callers that layer their own error taxonomy or need a non-default cap can map the result themselves. The returned error is:

  • a *http.MaxBytesError (test with errors.As) when the body exceeded maxBytes — the caller decides 413 vs 400;
  • ErrTrailingData when a second JSON value follows the first;
  • otherwise the underlying *json.SyntaxError / *json.UnmarshalTypeError / io.EOF (empty body) for a malformed body — typically a 400.

It is the shared mechanism behind DecodeBody: DecodeBody is DecodeJSONInto at the MaxJSONBody cap plus a coded-400 WriteError on any error. Apps with a bare {"error":…} envelope, a per-endpoint size cap, or a 413/400 split (see the webhttp consumers) build their own one-liner on it instead of reproducing the cap + decode + trailing-check by hand.

func InlineScriptHashes

func InlineScriptHashes(html []byte) []string

InlineScriptHashes scans HTML for inline <script> elements (those WITHOUT a src attribute) and returns a CSP source token 'sha256-<base64>' for each, hashing the exact bytes between the element's '>' and its '</script>' — precisely the content a browser hashes for a Content-Security-Policy script-src hash. External (src=) scripts are skipped; 'self' already covers them.

It exists so an app serving a build-controlled embedded page (an importmap plus a module bootstrap are the classic pair) can pin its script-src to exact hashes instead of 'unsafe-inline', computing the tokens at startup from the very bytes it will serve — a policy that then survives any reformat or rebuild with no hand-maintained hash constant. Feed the result into the app's policy string and pass that via WithCSP; the library builds no policy itself (a CSP is application-specific).

The scanner is byte-precise and dependency-free: case-insensitive tag matching on a tag-name boundary at BOTH ends (neither "<scriptfoo" nor "</scriptfoo>" belongs to this element, matching the tokenizer), quote-aware attribute scanning (a '>' or "src=" inside a quoted attribute value does not confuse it), and "src" matched only as a real attribute name (srcset and data-src do not count). It is an extractor for pages the APP controls, not an HTML sanitizer for untrusted input. It returns an empty slice on script-less or malformed input — an element whose end tag is truncated by end-of-input has no span a browser would hash, so it yields nothing; a caller whose page is known to carry inline scripts should treat an empty result as a malformed build and fail startup rather than degrade its policy.

func InlineStyleHashes

func InlineStyleHashes(html []byte) []string

InlineStyleHashes scans HTML for inline <style> elements and returns a CSP source token 'sha256-<base64>' for each, hashing the exact bytes between the element's '>' and its '</style>' — precisely the content a browser hashes for a Content-Security-Policy style-src hash.

It is the style-src counterpart of InlineScriptHashes and shares its scanner core, so the byte-boundary and malformed-tag behavior cannot drift between the two. It exists for the same reason: an app serving a build-controlled embedded page can pin style-src to exact hashes instead of 'unsafe-inline', computed at startup from the very bytes it will serve. A pre-JS loading overlay whose CSS must paint before the external stylesheet loads is the classic case — and one a hash suits well, because that block is build-controlled.

There is no skip rule, unlike the script scanner's external-src case: a <style> element always carries its content inline (a stylesheet reference is <link rel="stylesheet">, which style-src covers via 'self'). A media attribute does not change what a browser hashes, so such blocks are hashed like any other.

Note what a style-src hash does NOT cover: inline style ATTRIBUTES (style="..."), which are governed by style-src-attr and need 'unsafe-hashes' rather than an element hash. This function is for <style> ELEMENTS only, so an app whose markup or renderer sets style attributes cannot drop 'unsafe-inline' on the strength of these tokens alone. A renderer driving CSSOM property setters (element.style.color = …) emits no attribute and is unaffected.

Same posture as the script scanner: an extractor for pages the APP controls, not an HTML sanitizer for untrusted input. It returns an empty slice on style-less or malformed input; a caller whose page is known to carry an inline style block should treat an empty result as a malformed build and fail startup rather than degrade its policy.

func JSONHeaders

func JSONHeaders(w http.ResponseWriter)

JSONHeaders sets the standard JSON response headers: an application/json content type and the X-Content-Type-Options: nosniff guard against MIME sniffing. Call it before WriteHeader.

The nosniff guard is set only when the header is still unset, so a stack that composes SecurityHeaders keeps that middleware as the header's single writer while a stack without it still gets the guard on every JSON body this library writes.

func LimitBody

func LimitBody(w http.ResponseWriter, r *http.Request, maxBytes int64)

LimitBody caps the request body at maxBytes by replacing r.Body with an http.MaxBytesReader. Call it before reading the body.

It writes NOTHING to w, so detecting and answering an over-limit body is the CALLER's job, on the read error — that error is the ONLY signal the condition reliably delivers:

webhttp.LimitBody(w, r, maxBytes)
body, err := io.ReadAll(r.Body)
if tooLarge, ok := errors.AsType[*http.MaxBytesError](err); ok {
	// tooLarge.Limit == maxBytes. The status is yours: 413, 400, or none
	// at all (log it and drop the request).
}

Every read path in the package keeps that contract: DecodeJSONInto returns the *http.MaxBytesError untouched, and DecodeBody maps it — like any other decode failure — to a 400.

That contract SURVIVES Go 1.27's re-implementation of encoding/json on top of encoding/json/v2, measured on the released go1.27.0 rather than on rc2: Decode over an http.MaxBytesReader still yields *http.MaxBytesError and errors.AsType still matches it. Recorded because the intermediate state looks alarming and invites a fix that is not needed — building with GOEXPERIMENT=jsonv2 on a Go 1.26 toolchain DOES break it (the read error arrives wrapped in a *json.SyntaxError whose Unwrap chain ends there), which is golang/go#77789, fixed by CL 748860 on 2026-03-06, well before the 1.27 freeze and therefore present in 1.27 but absent from the 1.26 patch line. So a jsonv2-experiment build on Go 1.26 is NOT a valid preview of 1.27 for this path; test against the real toolchain before concluding this contract needs decoupling from the decoder.

The connection-close signal, and when it is absent

http.MaxBytesReader also tells net/http that the request was too large, which makes the server add Connection: close and close the connection after the reply rather than draining the sender's remaining bytes. It delivers that by type-asserting an UNEXPORTED net/http interface on the ResponseWriter it was handed, so it reaches net/http ONLY when the writer is net/http's own — no third-party wrapper can satisfy an unexported method, and MaxBytesReader does not walk Unwrap itself. LimitBody therefore walks w's Unwrap chain (the http.ResponseController convention) and hands MaxBytesReader the writer at the end of it. The middlewares here that wrap the writer to record a status (Logging and Recoverer, via StatusRecorder) implement Unwrap, so a normal Chain keeps the signal.

It is still absent, with no way for this package to recover it, when:

  • some wrapper in the chain does not implement Unwrap() http.ResponseWriter (a third-party middleware): the walk stops at that wrapper;
  • the handler runs under RouteTimeout / http.TimeoutHandler, whose buffering writer is not unwrappable;
  • w is not a net/http writer at all (an httptest.ResponseRecorder).

In every one of those cases the read still fails with a *http.MaxBytesError — which is why the caller-side check above is the contract and the close is not. Independently of this signal, net/http closes the connection anyway when more than 256 KiB of the body is left unread.

func LoopbackRequest

func LoopbackRequest(r *http.Request) bool

LoopbackRequest reports whether a request is genuinely local: its socket PEER is loopback AND its Host header names the local host. Both legs are required, so either one failing refuses. It is the route-level gate for a loopback-only surface on an otherwise-unauthenticated port — an in-container agent running curl localhost:PORT, an operator repair hook — and it decides admission only: the refusal's status, envelope and wording stay with the caller, as does any ADDITIONAL deny the app layers on top.

It consults exactly two fields, r.RemoteAddr and r.Host, and nothing else. The forwarded headers (X-Forwarded-For, X-Forwarded-Host, Forwarded) are IGNORED in both directions: their presence can never admit a request, and never refuse one either. That asymmetry is what makes the answer trustworthy — RemoteAddr is set by the server from the accepted connection (net.Conn.RemoteAddr().String()), so it cannot be spoofed at this layer, while any header can be. An app that wants to REFUSE on proxy provenance composes that deny around this predicate rather than finding it folded in.

Both legs fail CLOSED. A RemoteAddr that does not split as host:port (a portless value from a non-stdlib caller, an empty string) or whose host net.ParseIP refuses is not a loopback peer; a Host that CanonicalHost rejects canonicalizes to "" and names nothing. The Host leg accepts every well-formed spelling CanonicalHost collapses: "localhost" in any case, with or without a port or one trailing FQDN dot, 127.0.0.0/8, ::1, and bracketed IPv6 with or without a port.

The CONJUNCTION is the reusable unit, which is why it is what this library exports. A bare peer-only predicate is withheld BY DESIGN (see BindClass's rule: a peer is classified internally where a feature's own contract needs it, never handed out loose), because the peer leg alone invites exactly the misuse this export replaces. A DNS-rebound page reaches a server sharing its loopback interface with a LOOPBACK socket peer and the ATTACKER's name in Host, so a peer-only gate admits it (CWE-346); and after rebinding Origin and Host agree, so a same-origin check does not catch it either. Requiring the Host leg in the same call is what makes the shared unit safe to reach for — two separately exported halves would let a consumer ship half the check and believe it had the gate.

This is NOT HostPolicy, and cannot be assembled from one. HostPolicy evaluates its Host-only allowlist BEFORE the two-legged loopback exemption (Allows checks the allowlist map first), so a REMOTE caller sending Host: localhost is ADMITTED whenever that name is allowed — precisely the caller this predicate must refuse, and a name an operator has every reason to allow so their own browser reaches the service. An inactive policy (unset configuration) admits everything besides. The allowlist answers "is this Host one the operator named"; this answers "did this request come from inside".

func MethodNotAllowed

func MethodNotAllowed(w http.ResponseWriter, r *http.Request, allowed ...string)

MethodNotAllowed writes the 405 refusal for a request whose method the route does not support: it sets the Allow header to the allowed set (see SetAllow) and writes the standard error response (code "method_not_allowed"). It is the rejection half of RequireMethod, exported because a route may permit SEVERAL methods and so cannot express its refusal as a single-method guard:

// POST /things and GET /things are registered; HEAD is not served.
mux.HandleFunc("HEAD /things", func(w http.ResponseWriter, r *http.Request) {
	webhttp.MethodNotAllowed(w, r, http.MethodGet, http.MethodPost)
})

A handler that dispatches on the method itself (a switch over r.Method) calls it from the default branch with the same list. Either way the 405 carries the full Allow list RFC 9110 requires, instead of the one method a guard could name.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	rr := httptest.NewRecorder()
	// A route serving GET and POST refuses everything else, and RFC 9110
	// requires the 405 to advertise BOTH permitted methods, not just one.
	webhttp.MethodNotAllowed(rr, nil, http.MethodGet, http.MethodPost)
	fmt.Println(rr.Code)
	fmt.Println(rr.Header().Get("Allow"))
	fmt.Print(rr.Body.String())
}
Output:
405
GET, POST
{"error":"method not allowed","code":"method_not_allowed"}

func NewRequestID

func NewRequestID() string

NewRequestID returns a fresh request id: 16 cryptographically random bytes, hex-encoded to 32 characters. crypto/rand.Read never returns an error (since Go 1.24 it crashes the program irrecoverably if the platform random source fails), so id generation cannot degrade.

func NewServer

func NewServer(handler http.Handler, opts ...ServerOption) *http.Server

NewServer builds an *http.Server for handler with streaming-safe defaults: ReadHeaderTimeout 10s (a slowloris guard), IdleTimeout 120s, MaxHeaderBytes 1 MiB, and ReadTimeout/WriteTimeout left unset (0) so SSE, WebSocket, and other long-lived responses work out of the box. Options override the defaults.

Because ReadTimeout and WriteTimeout are unset by default, only header reading is time-bounded (by ReadHeaderTimeout); a slow request BODY is not. A non-streaming handler should add WithReadTimeout to bound slowloris-style slow bodies. A streaming handler, which cannot use a whole-request timeout, should instead apply per-request deadlines via http.ResponseController.SetReadDeadline/SetWriteDeadline. Note that MaxBytesReader (see LimitBody) bounds body SIZE, not the time taken to send it.

Fields left to the caller, and one that logs nothing

NewServer returns the *http.Server, so any field it does not set is reachable with a plain assignment and gets no option here — an option that only assigns a field of the value the constructor hands back adds surface and no capability. Three worth knowing about on Go 1.27:

  • Server.MaxHeaderValueCount caps how many header VALUES a request may carry, defaulting to http.DefaultMaxHeaderValueCount (500). Set it directly: srv.MaxHeaderValueCount = 64. Measured on go1.27.0, and the reason it is called out rather than merely left alone: the 431 is answered BELOW the handler, so a request refused by this cap produces NO access-log line from Logging and NO headers from SecurityHeaders — a refusal class an operator watching webhttp's access log cannot see. Cap header count at a proxy, or alert on the server's own error log, if that matters. (MaxHeaderBytes, which NewServer does set, refuses the same way.)
  • Server.DisableClientPriority = true restores round-robin HTTP/2 stream scheduling in place of Go 1.27's RFC 9218 client-priority handling. This library expresses no opinion: priority is a property of the workload, not of the plumbing, and NewServer leaves Protocols nil so HTTP/2 arrives only over TLS anyway.
  • Server.Protocols is nil, which is net/http's default set and does NOT include unencrypted HTTP/2. That is what keeps the ReadHeaderTimeout guard above in force: Go 1.27 clears the header deadline after accepting an unencrypted h2 connection, and that path is unreachable unless a caller opts in by setting Protocols with UnencryptedHTTP2.

func Ok

func Ok(w http.ResponseWriter)

Ok writes a 200 response with the JSON body {"ok":true}. It is the canonical success acknowledgement for an endpoint that has no other payload.

Example
package main

import (
	"fmt"
	"net/http/httptest"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	rr := httptest.NewRecorder()
	webhttp.Ok(rr)
	fmt.Print(rr.Body.String())
}
Output:
{"ok":true}

func ParseCIDRs

func ParseCIDRs(entries []string) (prefixes []netip.Prefix, invalid []string)

ParseCIDRs parses trusted reverse-proxy entries into the prefix set ResolveClient, ClientIP and WithClientIP take. An entry is a CIDR, masked to its network, or a bare IP, a single-host prefix; an IPv4-mapped entry of 96 bits or more becomes its IPv4 prefix, so both spellings of a network are one prefix. Entries are trimmed and blank ones skipped; one that parses as neither, a zoned address included, comes back in invalid, in input order, so a strict caller can reject the input and a lenient one can use the rest. An empty set trusts nothing.

func ProxiedRequest

func ProxiedRequest(h http.Header) bool

ProxiedRequest reports whether h carries any evidence the request was forwarded by a proxy or issued by a browser.

Exported alongside the middleware because the header SET is the drifting knowledge: two consumers had hand-rolled it, and a consumer that cannot adopt the middleware wholesale (one with its own admission pipeline) should still be able to share the list rather than maintain a third copy. It is a positive signal only — never treat a missing header as evidence of anything.

func ReadinessHandler

func ReadinessHandler(c ReadinessChecker) http.HandlerFunc

ReadinessHandler returns a handler that reports serving state as JSON: 200 with {"status":"ok"} when c reports ready, otherwise 503 with {"status":"unready","reason":"starting up or shutting down"}. Both responses carry Cache-Control: no-store.

This is the HTTP SERVING-STATE gate (note the lowercase "ok"), meant for a load balancer asking "should this instance receive traffic right now?". It is deliberately distinct from the cplieger health library's container file-marker probe, which answers {"status":"OK","timestamp":…} for a Docker HEALTHCHECK asking "is the process alive?". The two are complementary and are not the same endpoint.

no-store is not decoration. Under RFC 9111 a 200 GET carrying no explicit freshness information is HEURISTICALLY CACHEABLE, and the answer to "should this instance receive traffic right now" is the one answer in a service that is never valid a moment later. The unready direction is safe by accident (503 is not among the heuristically-cacheable statuses), so the reachable failure is the dangerous one: a cached "ok" outliving the readiness it reported, which keeps traffic arriving at an instance that has begun draining — defeating the gate at exactly the moment it exists for. Consumers that front this endpoint with a caching reverse proxy (the documented deployment shape for more than one of them) were relying on that proxy not to cache.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request id stored in ctx by WithRequestID, or "" if none is present.

func RequestLogger

func RequestLogger(next http.Handler, opts ...LogOption) http.Handler

RequestLogger returns middleware that gives each request a request id, echoes it on the response HeaderRequestID header, threads it through the request context (see RequestIDFromContext), and emits one access-log line at Info after next returns:

logger.Info("http", "method", …, "path", …, "status", …,
	"duration_ms", …, "request_id", …)

With WithClientIP the line additionally carries a "client_ip" attribute resolved by ClientIP (spoof-proof, honoring only the trusted proxy ranges passed to the option); WithClientIPFunc is the variant that resolves it with a caller-supplied function, for a dynamic (e.g. config-reloaded) trusted set. With WithPathFunc the recorded path is fn's return instead of r.URL.Path — the token-redaction middle ground between logging a credential-bearing path raw and skipping its access record entirely (fail-closed placeholder when the transform fails; see the option).

The two attacker-controlled attributes are bounded by default, whichever policy produced them: the path to 512 bytes cut on a rune boundary plus a truncation marker (WithMaxLoggedPath re-sets the cap), and the method to 24 bytes, over which it records a fixed "(overlong)" placeholder rather than a misleading prefix. Both bounds apply to the LOG only — routing, the status, and the response are unchanged.

It records the status via a StatusRecorder that stays transparent to http.ResponseController, so wrapped handlers can still Flush and Hijack. An inbound HeaderRequestID is reused when it satisfies ValidRequestID; otherwise a new id is minted with NewRequestID.

A request matched by WithSkipPaths or WithSkipFunc still gets an id minted, echoed, and threaded, but is served through the raw writer with no recorder, no access-log line, and no metric hook. WithSkipUpgrades removes the record of a request that actually SWITCHED PROTOCOLS (a completed WebSocket handshake), decided from the response instead of predicted from the request, so every refusal on the same route keeps its line; it can only remove a record, never restore one a skip rule dropped.

The access-log line and metric hook are emitted from a deferred call, so a handler that panics is still logged (the status shows the recorded value) before the panic continues up the stack to net/http.

func RequireMethod

func RequireMethod(w http.ResponseWriter, r *http.Request, method string) bool

RequireMethod reports whether the request method equals method. On a mismatch it writes the standard 405 via MethodNotAllowed, naming method as the only allowed one, and returns false, so a handler can guard with:

if !webhttp.RequireMethod(w, r, http.MethodPost) {
	return
}

A route that permits more than one method has no single method to require: route each method with the mux (net/http's method-prefixed patterns) or dispatch on r.Method, and refuse the rest with MethodNotAllowed so the 405 advertises the whole set.

func RouteMetricLabels

func RouteMetricLabels(r *http.Request) (method, path string)

RouteMetricLabels derives the bounded (method, path) label pair for a per-request HTTP metric. It is the pure primitive behind WithRecordRouteMetric, exported for any hook that already holds the request and wants the standard pair inside it — but the OPTION is the recommended path, because a helper only protects the consumers that remember to call it.

The method label is r.Method when it is one of the nine standard methods — GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE (RFC 9110 §9.3) and PATCH (RFC 5789) — and the fixed "other" bucket for everything else. Ten values, by construction, whatever arrives on the request line.

The path label is the route http.ServeMux matched: r.Pattern with the method prefix stripped ("GET /beat/{id}" records "/beat/{id}", so every beat id records as one series and an unknown id mints nothing), the pattern itself when it names no method ("/beat/{id}", a "/" catch-all), and the fixed "unmatched" marker when nothing matched (r.Pattern == "", e.g. net/http's own 404, or its 405 for a method that missed a method-bearing route). A host-qualified pattern ("GET example.com/beat/{id}") keeps its host — still a string the server registered, still bounded.

Every value on both labels is therefore either a pattern the SERVER registered or one of eleven fixed strings this package can return (the nine standard method names, the "other" bucket, the "unmatched" marker), so the series ceiling is ten times one more than the route table and no property of the traffic can widen it. That matters because the hook fires from the access-log defer, outside every app auth gate, and a series once minted is permanent for the process lifetime here AND in every observer scraping it.

The method comes from the REQUEST, bounded by the closed set, rather than from the matched pattern. Deriving it from the pattern is also bounded, but it makes http.ServeMux's HEAD-to-GET routing invisible: a HEAD probe against a GET-only pattern would record method="GET" while the access line for the same request records HEAD, so the log and the metric disagree about the commonest non-GET probe there is. Reading the closed set instead keeps them in agreement for all nine standard methods and still owes nothing to the route table.

ONE divergence from the access line remains, deliberately: for a NON-standard method the line records the token verbatim (bounded to 24 bytes, see boundLoggedMethod's marker) while this records "other". A log line is read to diagnose one request and needs the real value; a metric series is read in aggregate and needs a bounded name. When a metric shows "other" traffic, the access line for the same request_id says what the method was.

Caveat, inherited from the hooks: middleware between RequestLogger and the mux that replaces the request (r.WithContext and friends return a clone) leaves r.Pattern empty here, because the mux populated the clone. That reads as "unmatched" for every request — check it before believing a flat metric.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	// The labels for a request that matched "GET /beat/{id}". A HEAD probe
	// records HEAD, not the pattern's GET, so the metric and the access line
	// agree on the method.
	head := &http.Request{Method: http.MethodHead, Pattern: "GET /beat/{id}"}
	fmt.Println(webhttp.RouteMetricLabels(head))

	// A non-standard method collapses onto one bucket, so a caller cannot mint a
	// series per invented token. The access line still records the token itself.
	probe := &http.Request{Method: "PROPFIND", Pattern: "/"}
	fmt.Println(webhttp.RouteMetricLabels(probe))

	// Nothing matched: every unrouted request shares one path label.
	missed := &http.Request{Method: http.MethodGet}
	fmt.Println(webhttp.RouteMetricLabels(missed))
}
Output:
HEAD /beat/{id}
other /
GET unmatched

func RouteTimeout

func RouteTimeout(h http.Handler, d time.Duration, msg string) http.Handler

RouteTimeout wraps h with http.TimeoutHandler so a handler that runs longer than d is cut off with a 503, but replaces net/http's plain-text/HTML timeout body with a JSON ErrorResponse ({"error":msg,"code":"timeout"}) served as application/json. An empty msg defaults to "request timed out".

A non-positive d disables the timeout: h is returned unwrapped, so its response passes through untouched with no 503 relabeling. (http.TimeoutHandler with a zero or negative duration would otherwise fire the timeout immediately.)

The JSON relabeling keys on status alone: any 503 that reaches the client WITHOUT a Content-Type already set is served as application/json, because the wrapper cannot tell http.TimeoutHandler's own timeout envelope apart from a downstream handler's intentional 503. A handler that emits its own 503 must therefore set an explicit Content-Type, or it will be relabeled application/json (its body bytes are left unchanged; only the headers are added).

It CANNOT wrap streaming or hijacking handlers: http.TimeoutHandler buffers the entire response in memory to be able to discard it on timeout, so SSE, WebSocket upgrades, and other long-lived or flushing responses do not work through it. Apply RouteTimeout only to bounded request/response handlers, and use per-request deadlines (http.ResponseController.SetWriteDeadline) for streaming routes instead.

That buffering writer is also not unwrappable, so a handler under it cannot reach the ResponseWriter net/http gave the request: on a body-reading route, LimitBody's over-limit read still fails with a *http.MaxBytesError but net/http is never told to close the connection (see LimitBody).

The timeout envelope follows the package's universal request-id correlation scheme, exactly like WriteError: it is rendered per request, so when the request context carries an id (RouteTimeout composed under Logging / RequestLogger) the 503 body includes request_id, and when it does not the field is omitted. http.TimeoutHandler requires the body pre-rendered at construction, which is why the handler is assembled per request around the request-scoped envelope.

func Run

func Run(ctx context.Context, srv *http.Server, ln net.Listener, onShutdown func(ctx context.Context), opts ...RunOption) error

Run serves srv on ln until ctx is cancelled, then shuts down within one grace period (WithShutdownGrace): the WithPreDrain hook, srv.Shutdown, then onShutdown if non-nil, all bounded by the same deadline. When Serve returns before ctx is cancelled, only the WithServeExit hook runs. Run returns a serve error first, else the shutdown error (see ErrShutdownGraceExpired), and treats http.ErrServerClosed as a clean stop. It sets srv.ConnState, calling any hook already set first, and closes connections that have sent no request once srv.Shutdown starts. Bind ln first so a port-in-use error precedes Run.

func SetAllow

func SetAllow(w http.ResponseWriter, allowed ...string)

SetAllow sets the RFC 9110 Allow header to the set of methods a route advertises as supported: the entries joined with ", " (RFC 9110 Section 10.2.1, "Allow = #method"). A 405 response MUST carry the header, which is why MethodNotAllowed and RequireMethod both render it here; the spec permits it on any other response too, so an OPTIONS handler can advertise its route with the same call.

Entries are method tokens (http.MethodGet and friends) emitted verbatim, because a method token is case-sensitive (Section 9.1): the header must name what the route actually compares a request method against, not a canonicalized spelling of it. An empty entry is dropped, so a set assembled from configuration cannot emit the empty list element a sender must not generate (Section 5.6.1.1), and an exact duplicate is collapsed because the field names a set. Passing no methods sets the header to the empty value, which is the spec's own encoding for "this resource allows no methods" — a route disabled by configuration — and keeps the 405's MUST satisfied.

HEAD is deliberately NOT implied by GET. The field reports what THIS route advertises, and a route may refuse HEAD on purpose: net/http's ServeMux serves a HEAD request from a GET pattern, so a route whose GET carries a side effect (recording a heartbeat, say) registers HEAD separately to reject it and must not then advertise it. Pass http.MethodHead explicitly when the route serves it.

func StaticHandler

func StaticHandler(fsys fs.FS, opts ...StaticOption) (http.Handler, error)

StaticHandler serves fsys, typically an embed.FS, whose zero ModTime leaves a bare http.FileServer nothing to revalidate on. It reads the tree once and gives each file a sha256 ETag and, when smaller, a gzip body. A known asset carries its ETag, Cache-Control and Vary: Accept-Encoding; a GET or HEAD offering gzip without Range gets the gzip body under its own "-gz" ETag. Everything else falls through to http.FileServer. The error is non-nil only when walking fsys fails.

func ValidRequestID

func ValidRequestID(s string) bool

ValidRequestID reports whether s is a well-formed request id: between 1 and 64 characters, each an ASCII letter, digit, underscore, or hyphen. Anything else (empty, too long, or containing another byte) is rejected, so a client cannot smuggle log-forging newlines or header-splitting content through the echoed id.

Example
package main

import (
	"fmt"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	fmt.Println(webhttp.ValidRequestID("abc-123_XYZ"))
	fmt.Println(webhttp.ValidRequestID("bad id"))
}
Output:
true
false

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

WithRequestID returns a copy of ctx carrying the request id.

func WriteError

func WriteError(w http.ResponseWriter, r *http.Request, status int, code ErrorCode, msg string)

WriteError writes an ErrorResponse with the given HTTP status: msg becomes Error, code becomes Code, and the request id is pulled from the request context (via RequestIDFromContext) so a client can correlate the failure with the access log. It is nil-safe: when r is nil the RequestID field stays empty.

The code is the machine token and msg is the sentence for a human; they are separately typed so the pair cannot be handed over transposed (see ErrorCode). A code that is not a well-formed token is replaced with InvalidErrorCode rather than emitted, and never panics — this runs per request on an error path.

WriteError ships the MECHANISM only. Each consuming application keeps its own named-helper and error-code taxonomy on top of it.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	rr := httptest.NewRecorder()
	// r may be nil; the request_id field is then omitted.
	webhttp.WriteError(rr, nil, http.StatusBadRequest, "bad_request", "invalid payload")
	fmt.Print(rr.Body.String())
}
Output:
{"error":"invalid payload","code":"bad_request"}

func WriteJSON

func WriteJSON(w http.ResponseWriter, v any)

WriteJSON writes v as a JSON body with a 200 status.

func WriteJSONStatus

func WriteJSONStatus(w http.ResponseWriter, code int, v any)

WriteJSONStatus sets the JSON headers, writes the status code, and encodes v as the response body. The status is committed before encoding begins, so an encode failure cannot change it; such a failure is logged at Warn rather than returned, because the response line is already on the wire.

Types

type BindClass

type BindClass int

BindClass is the network-exposure classification of a configured listen address — the value an operator puts in a bind knob ("KWEB_ADDR", "WT_ADDR", "LISTEN_ADDR") before the process calls net.Listen. Apps use it at boot to drive exposure POLICY (warn that an unauthenticated surface is reachable beyond loopback, flag an open-and-public deployment); the classification itself is the shared mechanism.

Classify the CONFIGURED bind only. A live socket peer (r.RemoteAddr) is a different concern with different inputs (the Go server always supplies a parseable ip:port, and the question is "who connected", not "where do I listen"); peer decisions belong to their own gates (e.g. HostPolicy's loopback carve-out), never to this classifier.

const (
	// BindInvalid means the address does not parse as "host:port"
	// (net.SplitHostPort rejected it: no port, stray brackets, too many
	// colons). The zero value, so an uninitialized classification never
	// reads as a safe loopback bind. What to do with it is app policy —
	// see the recipes on ClassifyBind.
	BindInvalid BindClass = iota
	// BindLoopback means the host names the loopback interface explicitly:
	// a 127.0.0.0/8 or ::1 literal (including 4-in-6 forms of 127/8), or
	// the name "localhost" under ASCII case folding, so "LocalHost" and
	// "LOCALHOST" match and "localhoſt" (U+017F) does not — see
	// equalASCIIFold for why the fold stops at ASCII. Only these are "safe"
	// in the exposure sense: an IP-literal loopback bind is unreachable from
	// other machines by kernel routing, and a "localhost" bind is
	// loopback-only under the standard resolver mapping (RFC 6761 §6.3 — a
	// SHOULD an operator's hosts file can override; the classifier reads the
	// text, not the resolver).
	BindLoopback
	// BindExposed means the listener is (or may be) reachable beyond
	// loopback: a wildcard bind (empty host, "0.0.0.0", "::"), any
	// routable IP literal, or any hostname other than "localhost". A
	// hostname is classified WITHOUT resolution — fail-public: the
	// classifier cannot know what "myhost" resolves to at bind time, and
	// resolving here would race the bind itself. A zoned IPv6 literal
	// ("::1%lo") also lands here via the hostname path (net.ParseIP
	// rejects zones); binding one is exotic enough that the fail-public
	// reading is the safe one.
	BindExposed
)

func ClassifyBind

func ClassifyBind(addr string) BindClass

ClassifyBind classifies a configured listen address of the "host:port" form net.Listen accepts. The HOST decides the class; the port is not validated (net.Listen owns that failure, with a better error than any pre-check here could give).

An address net.SplitHostPort cannot split returns BindInvalid, and what that means is deliberately the caller's policy. The three shipped policies, as recipes:

// Fail-silent (web-terminal-kiro): an unparseable addr will fail at
// Listen anyway; only a definite exposure warrants the warning.
if webhttp.ClassifyBind(addr) == webhttp.BindExposed { warn(...) }

// Fail-public (pg-autodump): a spurious warning is preferable to a
// silently unflagged open endpoint.
if webhttp.ClassifyBind(addr) != webhttp.BindLoopback { warn(...) }

// Classify-the-unsplit-input (web-terminal-server): a portless value
// like "127.0.0.1" is read as a bare host and classified anyway.
class := webhttp.ClassifyBind(addr)
if class == webhttp.BindInvalid { class = webhttp.ClassifyBindHost(addr) }
if class != webhttp.BindLoopback { warn(...) }

No name resolution is performed and no repair is attempted; like CanonicalHost, the classifier reports what the input IS rather than guessing what the operator meant.

func ClassifyBindHost

func ClassifyBindHost(host string) BindClass

ClassifyBindHost classifies a bare bind host (no port): the host half of a listen address, or a whole portless bind value under the classify-the-unsplit-input recipe above. It never returns BindInvalid — a bare host always classifies: "localhost" (any case) and loopback IP literals are BindLoopback; everything else, including the empty string (the wildcard "listen on all interfaces" host), unspecified addresses ("0.0.0.0", "::"), routable IPs, and unresolved hostnames, is BindExposed.

func (BindClass) String

func (c BindClass) String() string

String returns the classification as a short lowercase word for log attributes: "invalid", "loopback", or "exposed".

type ClientResolution

type ClientResolution struct {
	// IP is the client: the X-Forwarded-For entry the walk chose when
	// Forwarded, otherwise Peer.
	IP netip.Addr
	// Peer is the host of r.RemoteAddr, unmapped; the zero Addr when it is
	// not an IP address.
	Peer netip.Addr
	// Forwarded reports that IP came from X-Forwarded-For, which is read only
	// when Peer is trusted.
	Forwarded bool
	// UntrustedForwarding reports that a peer outside the trusted set sent a
	// Forwarded, X-Forwarded-For or X-Real-IP field holding a non-empty list
	// element, which was ignored.
	UntrustedForwarding bool
	// IgnoredPublic reports that such an ignored header named a public
	// address: global unicast and outside RFC 1918 and RFC 4193.
	IgnoredPublic bool
}

ClientResolution is ResolveClient's answer: the client address and how it was found.

func ResolveClient

func ResolveClient(r *http.Request, trusted ...netip.Prefix) ClientResolution

ResolveClient resolves r's client against the trusted proxy prefixes, which must hold every hop, or the missing one is the client. Only a trusted peer has X-Forwarded-For read, from the right past trusted hops: a proxy appends the peer it saw, so the first untrusted entry is the client; a non-address entry or trusted hops only answer the peer. A field of over 64 entries, or a Forwarded element of over 16 pairs, is invalid whole and names no address. X-Real-IP and Forwarded never set IP: Caddy passes a client's copy through (https://caddyserver.com/docs/caddyfile/directives/reverse_proxy#defaults). Addresses compare unmapped, so a dual-stack IPv4 peer matches; a zone never does.

type ErrorCode

type ErrorCode string

ErrorCode is the MACHINE-READABLE token carried in the error envelope's "code" field — the value a client switches on and an operator's log query and alert rules key on. It is a distinct type from the human message so the two cannot be transposed at a call site: WriteError, WithHostAllowlistError and WithRateLimitError all take the pair (ErrorCode, string) in that order, and handing them a message-shaped value where the code goes is a compile error wherever either side is a typed constant or a variable.

The grammar is a token, not a sentence: lowercase ASCII letters, digits and underscores — "host_not_allowed", "rate_limited", "too_many_auth_failures". That is what every code in this library and in every consuming application already spells, so it is written down here rather than left to convention. A code containing a SPACE is a bug, not a message: the sentence belongs in the msg argument beside it, and a code is not a place to put prose.

The empty code is legal and means "omit the field": ErrorResponse.Code is omitempty, so an application with a bare {"error":…} taxonomy passes "" and gets no code on the wire.

A malformed code is NOT repaired and does NOT panic — see errorEnvelope: the envelope encoder substitutes the fixed InvalidErrorCode token so the machine slot always holds a machine value, and logs the offending code once per process.

const InvalidErrorCode ErrorCode = "invalid_error_code"

InvalidErrorCode is what the envelope encoder emits in place of a code that does not match ErrorCode's grammar. It is a code of its own rather than a reused "internal_error" so that a broken code is distinguishable on the wire from a genuine internal fault (the request's status is unchanged, and a 400 must not start claiming a server error), and rather than an empty code so it is distinguishable from an application that deliberately omits the field. This mirrors the access log's separation of "(path-redaction-failed)" — the policy itself broke — from "(unmatched)", a routine outcome.

type ErrorResponder

type ErrorResponder func(w http.ResponseWriter, r *http.Request, status int, code ErrorCode, msg string)

ErrorResponder renders an error response body. It has the exact signature of WriteError, which is its canonical instance and the library-wide default, so the JSON envelope is the zero-config behavior. Middleware that emits an error body (Recoverer via WithRecoverResponder, RateLimiter via WithRateLimitResponder) accepts one so a non-JSON endpoint - an XML or plain-text service - can keep its error body on its own content type instead of the default JSON. A responder owns writing the status and any headers, and is invoked only when the response has not been committed.

A responder receives the ErrorCode as the library resolved it from its caller — unvalidated, because the grammar is enforced by the JSON envelope encoder and a responder rendering another content type owns its own body. A responder that emits the code into a machine-readable slot should route it through this package's WriteError, or check it the same way.

type ErrorResponse

type ErrorResponse struct {
	// Error is the human-readable error message.
	Error string `json:"error"`
	// Code is an optional machine-readable error code.
	Code ErrorCode `json:"code,omitempty"`
	// RequestID is the request id for log correlation, when available.
	RequestID string `json:"request_id,omitempty"`
}

ErrorResponse is the JSON error envelope written by WriteError. Code and RequestID are omitted from the output when empty.

type GzipOption

type GzipOption func(*gzipConfig)

GzipOption configures Gzip.

func WithGzipMinBytes

func WithGzipMinBytes(n int) GzipOption

WithGzipMinBytes sets the smallest body Gzip compresses, 1024 bytes by default; a shorter body is sent as written. An n below 1 compresses every non-empty body.

func WithGzipSkip

func WithGzipSkip(skip func(*http.Request) bool) GzipOption

WithGzipSkip makes Gzip hand a request for which skip reports true to the next handler unwrapped, with no Vary added: for a route whose writes must reach the client as they happen, such as an event stream or a WebSocket. A nil skip is ignored.

func WithGzipTypes

func WithGzipTypes(types ...string) GzipOption

WithGzipTypes sets the media types Gzip compresses, replacing the default "application/json" and "+json". An entry is a type/subtype, matched against the Content-Type after mime.ParseMediaType (case-folded, parameters dropped), or a "+suffix", matched against the subtype's structured suffix after its last "+" (RFC 6839). A Content-Type that fails to parse is never compressed. With no entries nothing is compressed. It panics on an entry of neither form, or one holding a wildcard.

type HSTS

type HSTS struct {
	// MaxAge is how long a browser should keep enforcing HTTPS for the host.
	MaxAge time.Duration
	// IncludeSubdomains extends the policy to every subdomain
	// (includeSubDomains). Set it only when every subdomain is served over
	// HTTPS; a browser that has seen it will refuse a plain-HTTP subdomain for
	// the whole MaxAge window.
	IncludeSubdomains bool
	// Preload asks for inclusion in the browsers' built-in preload list, so the
	// very first request to the host is upgraded. It REQUIRES IncludeSubdomains
	// (see HSTS.Validate) and, for an actual submission, a MaxAge of at least a
	// year. Preloading is effectively permanent from an operations point of
	// view: removal takes months to reach users.
	Preload bool
}

HSTS is the Strict-Transport-Security policy passed to WithHSTS. The fields are named rather than positional because two of them are booleans standing for different directives: as a pair of adjacent arguments they could be handed over transposed and the header would still build.

The zero value is MEANINGFUL but is not "off": it renders "max-age=0", the directive that tells a browser to FORGET an HSTS policy it already holds for the host. HSTS off is leaving the option out of SecurityHeaders entirely.

A negative MaxAge is clamped to zero (same "forget it" instruction), and MaxAge is truncated to whole seconds, which is the only unit the header has.

func (HSTS) Validate

func (h HSTS) Validate() error

Validate reports whether the policy is internally consistent: it returns ErrHSTSPreloadWithoutSubdomains when Preload is set without IncludeSubdomains, ErrHSTSPreloadMaxAgeTooShort when Preload is set with a MaxAge under one year (which also catches the classic unit mistake — an integer count of seconds assigned to a time.Duration field is nanoseconds, so 31536000 renders max-age=0, "forget me", beside "preload me"), and nil otherwise.

It is the STRICT door for a caller that builds its HSTS value from configuration and wants to refuse to boot on a contradiction — the same split ParseCIDRs and ParseHostList offer, where the invalid input is returned and the caller decides between rejecting it and proceeding. WithHSTS itself takes the lenient half of that split, because a SecurityOption has no way to return anything: it drops the offending directive and logs.

type HostAllowlistOption

type HostAllowlistOption func(*hostPolicyConfig)

HostAllowlistOption configures a HostPolicy built by ParseHostList.

func WithHostAllowlistError

func WithHostAllowlistError(code ErrorCode, msg string) HostAllowlistOption

WithHostAllowlistError sets the error code and message written in the 403 JSON envelope (via WriteError) when a request's Host is not allowed. Defaults to "host_not_allowed" / "host not allowed". Override it to name the app's own configuration knob, e.g. "host not allowed; add it to KWEB_ALLOWED_HOSTS".

code is the machine token and msg the sentence; they are separately typed (see ErrorCode) so the pair cannot be supplied transposed. An empty code omits the field, which is how an app with a bare {"error":…} taxonomy keeps its envelope shape.

func WithLoopbackExempt

func WithLoopbackExempt(exempt bool) HostAllowlistOption

WithLoopbackExempt selects whether a request is admitted when BOTH its socket peer and its Host are loopback, regardless of the allowlist — the container-internal carve-out. Enabled (true) it keeps a service's own loopback clients working under any allowlist: a baked Docker healthcheck (curl http://127.0.0.1:PORT), an in-container agent hitting localhost, a sidecar probe. Without it, an allowlist of browser-facing hostnames rejects those callers and can brick a health signal.

The carve-out is unreachable by the attacks a host allowlist defends against. A DNS-rebinding request carries the ATTACKER'S hostname in Host, so it fails the loopback-Host test even when it originates from a browser on this same machine (a loopback peer); and a remote client forging Host: 127.0.0.1 is not a loopback socket peer, so it fails the peer test. Both conditions must hold, and only genuinely local traffic can satisfy both.

The default (false) matches leaving the option out: a bare allowlist rejects everything not listed, loopback included. Passing false explicitly is how a caller threads its own computed flag — a config field, an env var — without branching around the option, and options are last-wins, so a later WithLoopbackExempt(false) closes a carve-out an earlier true opened. Opt in when the service runs behind a loopback health check or serves in-container clients.

type HostPolicy

type HostPolicy struct {
	// contains filtered or unexported fields
}

HostPolicy is an immutable, canonicalized exact-match Host allowlist. Build one with ParseHostList and apply it with Middleware; the same policy answers the per-request decision through Allows. The zero value and a nil pointer are both inactive (permissive), so a policy parsed from unset configuration is a safe pass-through.

func ParseHostList

func ParseHostList(entries []string, opts ...HostAllowlistOption) (policy *HostPolicy, invalid []string)

ParseHostList parses operator-supplied allowlist entries (a config array or a comma-split environment variable) into a HostPolicy, returning the entries it could not use separately — a shape deliberately identical to ParseCIDRs so a strict caller can reject bad input while a lenient caller logs it and proceeds.

Each entry is trimmed; a blank entry is skipped and does not engage the gate. A usable entry is canonicalized via CanonicalHost and added to the allowlist. An entry that is not a well-formed host[:port] under CanonicalHost's strict grammar is reported as invalid (returned, never added): a pasted URL ("http://example.com"), a lone port (":9848") that belongs in the bind address, bracket or colon garbage, a non-ASCII name (configure the Punycode A-label instead), or an IP-like numeric string that is not a valid address ("127.0.0.001").

Activation, and the fail-closed contract: the policy is INACTIVE only when no non-blank entry was supplied at all (unset or all-whitespace configuration) — then Middleware is a pass-through and Allows returns true, the backward-compatible "accept every Host" default. As soon as ANY non-blank entry is supplied the gate is ACTIVE, even if every entry was invalid: a misconfigured allowlist (all entries malformed) then rejects every request rather than silently disabling the protection. Because invalid entries are returned rather than retained as unmatchable keys, a caller that wants to fail loud can inspect the invalid slice at startup and refuse to boot; a caller that wants to proceed logs it and runs with the valid subset (or, when the subset is empty, a fail-closed deny-all).

Pair it with WithLoopbackExempt for a containerized service whose own loopback health check or in-container clients must keep working, and with WithHostAllowlistError to name the app's configuration knob in the 403.

func (*HostPolicy) Active

func (p *HostPolicy) Active() bool

Active reports whether the gate is engaged. A policy parsed from unset or all-blank configuration is inactive: Middleware is a pass-through and Allows returns true for every request. A nil policy is inactive.

func (*HostPolicy) Allows

func (p *HostPolicy) Allows(r *http.Request) bool

Allows reports whether the request is admitted. An inactive (or nil) policy admits every request. An active policy admits a request only when its canonicalized Host is in the allowlist, or — when WithLoopbackExempt was set — when both the socket peer and the Host are loopback. r.Host is the only host value consulted; X-Forwarded-Host is deliberately ignored (it is client-controlled and this check must hold on the direct-exposure path). A malformed Host canonicalizes to "" and can never match.

func (*HostPolicy) Middleware

func (p *HostPolicy) Middleware() Middleware

Middleware returns the allowlist as webhttp middleware. An inactive (or nil) policy returns the next handler unwrapped — the "off" contract shared with RateLimiter and RouteTimeout, so a policy from unset configuration adds no overhead. An active policy rejects a request whose Host is not allowed with a 403 via WriteError (code and message set by WithHostAllowlistError), before the next handler runs.

Placement: put it OUTERMOST among request-authorization middleware, before a cross-origin or CSRF check, so a disallowed host is rejected before any route runs — a DNS-rebinding request makes Origin and Host agree, so a same-origin check alone would admit it; the exact-Host allowlist is what breaks that chain (CWE-346).

func (*HostPolicy) Size

func (p *HostPolicy) Size() int

Size reports the number of valid, canonicalized hosts in the allowlist (excluding entries ParseHostList reported as invalid). A nil policy has size zero.

type LogOption

type LogOption func(*logConfig)

LogOption configures RequestLogger.

func ProbeLogLevel

func ProbeLogLevel(paths ...string) LogOption

ProbeLogLevel is the shared access-log level policy for machine-probe endpoints (health checks, readiness probes, metrics scrapes). A request whose r.URL.Path exactly matches one of paths logs at Debug on success (status < 400), Warn on a 4xx and Error on a 5xx, so a healthy probe stays quiet and a failing one surfaces; every other request stays at Info. It is a WithLogLevel policy, so the two are mutually exclusive (last applied wins); a skipped path never consults it, and a panicking policy falls back to Info. With no paths every request logs at Info.

func WithClientIP

func WithClientIP(trusted ...netip.Prefix) LogOption

WithClientIP adds a "client_ip" attribute set to ClientIP(r, trusted...), for example with ParseCIDRs's prefixes. The attribute is omitted unless this option is supplied. It is resolved once per request inside the deferred access log, so skipped paths pay nothing.

func WithClientIPFunc

func WithClientIPFunc(fn func(*http.Request) string) LogOption

WithClientIPFunc is like WithClientIP but resolves the "client_ip" attribute with a caller-supplied function instead of a fixed trusted-proxy set. Use it when the trusted set is not known at construction — e.g. it is reloaded from config at runtime behind a hot-reloadable resolver — or when client-IP resolution is otherwise app-specific: fn is called once per logged request (never on a skipped path), and its result is logged verbatim as "client_ip". It composes with WithRecordMetric. WithClientIP and WithClientIPFunc both enable the attribute and are mutually exclusive; whichever is applied last wins. A nil fn is ignored (matching the package's skip-nil option convention), so a trailing WithClientIPFunc(nil) neither enables the attribute nor clears a prior WithClientIP.

func WithLogLevel

func WithLogLevel(fn func(r *http.Request, status int) slog.Level) LogOption

WithLogLevel sets the LEVEL POLICY for the access-log line: fn is called once per logged request with the request and the final status, and the line is emitted at the returned level. The default without this option is slog.LevelInfo, unchanged. The hook chooses the level only — the line's attributes and emission rules (deferred emit, skip paths) are the logger's fixed mechanism. ProbeLogLevel is the named preset over this hook for the routine-machine-probe case; reach for the raw hook only when a custom policy is genuinely needed.

The canonical use is scrape-noise control on a polled service: map 2xx/3xx to slog.LevelDebug so a 15-second Prometheus scrape stays out of the log stream at the default level while staying visible under LOG_LEVEL=debug, and raise 4xx to Warn / 5xx to Error so failures surface. Because fn also receives the request, a policy can key on the path instead (quiet only the scrape route, keep everything else at Info).

A request suppressed by WithSkipPaths or WithSkipFunc emits no line at all, so fn is never called for it. A panicking fn is contained: the failure is logged and the line falls back to Info, mirroring the package's other callback guards. A nil fn is ignored (the skip-nil option convention).

func WithLogger

func WithLogger(l *slog.Logger) LogOption

WithLogger sets the slog.Logger used for access-log lines. Defaults to slog.Default().

func WithMaxLoggedPath

func WithMaxLoggedPath(n int) LogOption

WithMaxLoggedPath sets the byte cap the access line applies to the recorded path, replacing the 512-byte default. Reach for it when the app's whole route table is short and a tighter log-line budget is worth more than the tail of a long path: knell serves /healthz, /metrics, and /beat/{id} with an id its config caps at 64 characters, so 128 covers every path it can legitimately answer.

n counts PATH bytes. An over-cap value keeps at most n of them, cut on a UTF-8 rune boundary, followed by the 14-byte truncation marker, so the attribute is at most n+14 bytes; a value within the cap is recorded byte-identical. The cap applies to whatever the path policy produced, including this package's own fail-closed placeholders, so the guarantee has no branch-shaped hole.

A non-positive n is ignored and the default stands (the skip-nil option convention). There is deliberately no way to switch the bound OFF: it exists because eight of the nine access-log consumers had no path bound of their own, so an option that could zero it would reopen precisely the hole it closes — and a config-driven 0 would do it silently.

func WithPathFunc

func WithPathFunc(fn func(*http.Request) string) LogOption

WithPathFunc sets the PATH POLICY for the access-log line: fn is called once per logged request, at emit time, and its return value replaces r.URL.Path as the recorded path. Use it when a route embeds a credential or other sensitive segment (e.g. "/api/sessions/{token}") that should be logged as a token-free template or truncated form — the middle ground between logging the raw path and losing the whole access record to WithSkipPaths or WithSkipFunc.

The returned value is "the path as recorded": it feeds the access line's "path" attribute, the legacy WithRecordMetric hook's path argument, and the "path" attribute of the package's hook-failure diagnostics. It feeds NEITHER request-derived metric hook: WithRecordMetricRequest receives the request itself and owns its own representation, and WithRecordRouteMetric's path label is the matched route, which is a bound of its own and not a redaction policy. fn's return is still length-bounded before it is recorded (512 bytes by default, WithMaxLoggedPath to change it): a transform is a REDACTION policy, and nothing about redacting a token also bounds the path it was in.

fn runs inside the deferred emit, after routing, so http.ServeMux has already populated r.Pattern (empty when nothing matched) and a transform may return the matched template with its own fail-closed fallback for unmatched requests. The WithRecordMetricRequest caveat applies equally: middleware between RequestLogger and the mux that replaces the request (r.WithContext and friends return a clone) hides the populated fields.

Skip predicates (WithSkipPaths, WithSkipFunc) always test the raw r.URL.Path, and a skipped request never calls fn.

Fail-closed: if fn panics or returns the empty string, the line records the "(path-redaction-failed)" placeholder — never the raw path — and a panic is additionally logged through the package's hook-isolation guard, whose own diagnostic also omits the raw path. A nil fn is ignored (the skip-nil option convention).

func WithRecordMetric

func WithRecordMetric(fn func(RequestMetric)) LogOption

WithRecordMetric registers a hook invoked once per logged request with the RequestMetric the access line RECORDED, so its two text fields carry exactly the log line's bounds: Method is capped at 24 bytes, which keeps an over-long token out of a metric label as well as out of the log, and Path is whatever the path policy produced, capped by WithMaxLoggedPath. With NO path policy configured — the default — Path is therefore the raw r.URL.Path truncated to 512 bytes. It fires from a deferred call, so a panicking handler is still recorded. Requests skipped via WithSkipPaths or WithSkipFunc are excluded from the hook as well as from access logging: a stream's open-to-close duration paired with a synthetic status is misleading, which is the whole reason the path is skipped.

Its bounds are LENGTH bounds, not cardinality bounds: a raw r.URL.Path under the cap is still one label value per URL a scanner invents, and a method under 24 bytes is still one per token. For a metric this hook is the wrong shape unless a path policy already collapses the path onto route templates — reach for WithRecordRouteMetric, whose labels are bounded by construction. The three metric options are mutually exclusive; whichever is applied last wins.

func WithRecordMetricRequest

func WithRecordMetricRequest(fn func(r *http.Request, status int, d time.Duration)) LogOption

WithRecordMetricRequest is the request-aware variant of WithRecordMetric: fn is invoked once per logged request with the *http.Request itself, the final status, and the latency. Because http.ServeMux assigns the matched pattern to the request in place, fn observes a populated r.Pattern after routing (empty when nothing matched, e.g. a 404), so a caller can key a metric on the route TEMPLATE rather than on the raw URL path. Caveat: middleware between RequestLogger and the mux that replaces the request (r.WithContext and friends return a clone) hides those fields — the mux populates the clone, not the request this hook received.

Prefer WithRecordRouteMetric. This hook hands fn the raw request, which makes the APP responsible for a bound it can get wrong, and one consumer did: it derived its labels from r.Method, wrote a comment asserting they were bounded, and shipped an attacker-controllable method label anyway, because it also registers a "/" catch-all — so its r.Pattern is never empty, the unmatched collapse it relied on can never fire, and every SPA fallthrough minted a series named by the caller. Nothing in the hook's signature could have caught that. WithRecordRouteMetric computes the bounded pair here and passes it in, so there is no derivation left for a consumer to get wrong; reach for this hook only when the metric genuinely needs something else from the request (say a per-tenant series keyed on an id the app validated itself), and use RouteMetricLabels when what it needs is the standard pair.

Like WithRecordMetric it fires from a deferred call (a panicking handler is still recorded) and is excluded on paths skipped via WithSkipPaths or WithSkipFunc. The three metric options are mutually exclusive; whichever is applied last wins. A nil fn is ignored (the package's skip-nil option convention), so a trailing WithRecordMetricRequest(nil) neither enables the hook nor clears a prior hook.

func WithRecordRouteMetric

func WithRecordRouteMetric(fn func(RequestMetric)) LogOption

WithRecordRouteMetric registers the metric hook whose labels THIS PACKAGE derives, and is the recommended one: fn is invoked once per logged request with the bounded (method, path) label pair RouteMetricLabels computes for the request, plus the final status and the latency. The app never receives the raw request through this option, so it has no derivation to get wrong — that is the whole reason the option exists rather than only the function. Safety here is a property of the wiring, not of every consumer remembering to reach for the right helper: WithRecordMetricRequest's godoc records the consumer that reached for the wrong one, believed otherwise, and shipped an attacker-controllable method label.

The labels are bounded BY CONSTRUCTION: the method is one of ten fixed values and the path is either a pattern the SERVER registered or the fixed "unmatched" marker. Cardinality is therefore a function of the route table, not of the traffic, which matters because the hook fires from the access-log defer — outside every app auth gate — and a series once minted is permanent for the process lifetime here AND in every observer scraping it. See RouteMetricLabels for each label's derivation and for the one deliberate divergence from the access line.

fn takes the same RequestMetric as WithRecordMetric, so switching a consumer from the unbounded hook to this one changes the option name and nothing else, and one recording function can be passed to either.

Like the other metric hooks it fires from a deferred call (a panicking handler is still recorded), is excluded on paths skipped via WithSkipPaths or WithSkipFunc, and is isolated by a recover guard (a panicking hook skips this request's metric rather than killing the connection). The three metric options are mutually exclusive; whichever is applied last wins. A nil fn is ignored (the package's skip-nil option convention), so a trailing WithRecordRouteMetric(nil) neither enables the hook nor clears a prior hook.

The path policy options (WithPathFunc, WithTemplatePathsUnder, WithMaxLoggedPath) do NOT reach these labels: they govern the recorded path of the LOG LINE, while this hook's path is the matched route. A path policy and this hook are complementary, not alternatives.

func WithSkipFunc

func WithSkipFunc(fn func(*http.Request) bool) LogOption

WithSkipFunc registers a predicate; when it returns true for a request, that request is passed through WITHOUT an access-log line or metric (like a WithSkipPaths match), while the request id is still minted, echoed, and threaded. Use it for streaming routes with path parameters (e.g. "/ws/{id}") that an exact WithSkipPaths match cannot cover.

func WithSkipPaths

func WithSkipPaths(paths ...string) LogOption

WithSkipPaths marks exact request paths (compared against r.URL.Path) that should pass through WITHOUT an access-log line AND without a metric hook. Use it for long-lived streams (SSE, WebSocket) whose single open-forever request would otherwise emit one misleading high-latency line and a synthetic status at close. The request id is still minted, echoed, and threaded into the context for skipped paths. Because the match is exact, streaming routes with path parameters (e.g. "/ws/{id}") need WithSkipFunc instead.

func WithSkipUpgrades

func WithSkipUpgrades(skip bool) LogOption

WithSkipUpgrades selects whether the access record is suppressed for a request whose response SWITCHED PROTOCOLS — and for nothing else. Enabled (true) it is what a WebSocket route should use instead of a WithSkipFunc predicate that PREDICTS which requests will upgrade.

The decision comes from the response, not from the request. The record is suppressed when the recorded status is 101 (the handshake went through the ResponseWriter, as coder/websocket's WriteHeader(101)-then-hijack does) or when the handler hijacked the connection before recording anything at all (the handler wrote the handshake onto the connection itself, as gorilla/websocket does). Those are the two shapes a completed upgrade takes, and in both the exchange has ENDED rather than completed, so the one line that would be emitted when the socket finally closes — hours later, carrying a session-length duration and a status net/http never sent — describes something that never happened. Every OTHER outcome on the same route keeps its record with its real status, duration, request id, and client ip: the 400 for a malformed Sec-WebSocket-Key, the 403 for a disallowed origin, the 405 for a non-GET, the 426 for missing upgrade headers. Those refusals are what an operator greps for when a browser cannot attach or a reverse proxy mangles a handshake.

Why the decision belongs here: a skip predicate has to answer before the handler runs, so it must model the handshake policy of whichever library will answer the request, and it drifts when that library changes. A consumer's predicate checked that Sec-WebSocket-Key was present exactly once; coder/websocket base64-decodes that header and requires exactly 16 bytes, answering 400 otherwise, so every malformed-key 400 was suppressed as if it had upgraded — as was the cross-origin 403 the same predicate could not model — losing status, duration, request id, and client ip for exactly the refused requests worth seeing. The fact the predicate was guessing at is known HERE, once the response exists.

The interaction with the skip options is one-way. WithSkipPaths and WithSkipFunc are evaluated before the handler and bypass the recorder entirely, so a request either of them matches is skipped whatever status it ends up with, and this option cannot bring its record back. This option only ever REMOVES a record that would otherwise have been emitted.

Suppression removes the whole record, the same pairing WithSkipPaths has and for the same reason: no access line and no metric hook, and neither the WithLogLevel policy nor a WithPathFunc / WithTemplatePathsUnder transform is consulted. The request id is still minted, echoed, and threaded, as on every path through this middleware. A handler that PANICS after the switch is not hidden by that: Recoverer logs the panic and its stack from its own line, which is where a crash mid-session belongs — the access line it would otherwise pair with says 101, not 500, because the status was decided at the handshake.

Two boundaries, because both KEEP their record:

  • A handler that never calls WriteHeader records the implicit 200 net/http sends. That is not 101, so an ordinary request that writes only a body is logged exactly as it is without this option.
  • A handler that writes an explicit status and THEN hijacks (an HTTP CONNECT tunnel answering 200) keeps its record with that status: it told us what it answered, and only 101 says "this is no longer an HTTP exchange". A consumer that wants such a tunnel silent still has WithSkipFunc, whose prediction problem does not apply to a test on the method.

It takes no status argument on purpose. 101 is the one status that means the exchange ended rather than completed, so a general skip-these-statuses option would add exactly one capability: silencing refusals. A 404 flood is a broken route and a 401 flood is an attack, and deleting their records is CWE-778 rather than noise control — which WithLogLevel (or the ProbeLogLevel preset) already does properly, by lowering a line's level instead of removing it.

HTTP/2's extended-CONNECT upgrade (RFC 8441) answers 2xx rather than 101 and is deliberately out of scope; it cannot arise for this option's audience anyway, since a server that hijacks to speak WebSocket needs HTTP/1.1.

The default (false) matches leaving the option out: every request keeps its record whatever status it ends on. Passing false explicitly is how a caller threads its own computed flag without branching around the option, and options are last-wins, so a later WithSkipUpgrades(false) restores the records an earlier true suppressed.

func WithTemplatePathsUnder

func WithTemplatePathsUnder(prefixes ...string) LogOption

WithTemplatePathsUnder declares URL prefixes whose concrete paths carry a CREDENTIAL, so the access log records the route template from r.Pattern instead ("/api/sessions/{id}", ServeMux's method prefix stripped). A path under a declared prefix that matched no route logs as the prefix plus "(unmatched)", never the raw path; a path outside every prefix logs unchanged. Pass the prefix the route-owning package exports (e.g. the terminal engine's SessionsSubtreePath). An empty prefix is ignored. This option and WithPathFunc replace each other: there is one recorded path, so the last applied wins.

type Middleware

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

Middleware is the standard net/http decorator shape: it wraps an http.Handler and returns a new one. It is a type alias, so any plain func(http.Handler) http.Handler value is a Middleware without conversion.

func FailedAuthRateLimit

func FailedAuthRateLimit(when func(*http.Request) bool, msg string) Middleware

FailedAuthRateLimit throttles requests for which when reports a failed credential through one aggregate bucket (burst 10, one token per 6s), answering 429 "too_many_auth_failures" with msg (empty: "too many failed authentication attempts"). A valid credential never draws a token; a nil when limits every request, for a caller that filters failed attempts first. when runs on every request, and the access-line flood is bounded only with the limiter outside Logging. Use RateLimiter directly for other numbers.

func Gzip

func Gzip(opts ...GzipOption) Middleware

Gzip returns middleware that gzips a response when the request offers gzip and the response has no Content-Encoding, a WithGzipTypes Content-Type, a status other than 1xx, 204, 206 or 304, and WithGzipMinBytes of body. Every response of a listed type with no Content-Encoding and a final status other than 204 carries Vary: Accept-Encoding, whatever the outcome; a compressed one drops Content-Length and Accept-Ranges and weakens its ETag. Until the size is reached the status and body are held back, and a Flush or the handler's return sends them as written. Place it inside Recoverer, so a panic before that point still answers 500.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	api := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"items":[` + strings.Repeat(`"item",`, 400) + `"item"]}`))
	})
	// The event stream must reach the client write by write, so it is skipped.
	events := func(r *http.Request) bool { return r.URL.Path == "/events" }
	h := webhttp.Chain(api, webhttp.Recoverer(), webhttp.Gzip(webhttp.WithGzipSkip(events)))

	for _, path := range []string{"/items", "/events"} {
		req := httptest.NewRequest(http.MethodGet, path, nil)
		req.Header.Set("Accept-Encoding", "gzip")
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		fmt.Printf("%s: %q\n", path, rec.Header().Get("Content-Encoding"))
	}
}
Output:
/items: "gzip"
/events: ""

func Logging

func Logging(opts ...LogOption) Middleware

Logging returns a Chain-composable Middleware wrapping RequestLogger with the given options. It is exactly RequestLogger in middleware form; use RequestLogger directly when you are not composing with Chain. See RequestLogger for the request-id and access-log behavior and the available LogOption values.

func LoopbackOnly

func LoopbackOnly(refuse http.Handler) Middleware

LoopbackOnly is the MIDDLEWARE half of the loopback-only admission decision, beside the LoopbackRequest predicate this package already exports.

The predicate answers "did this request come from inside" from the two fields that cannot be spoofed at this layer. This adds the second half every real consumer of that predicate turned out to need: a refusal on proxy and browser PROVENANCE headers. LoopbackRequest deliberately ignores those headers in both directions — they can never admit and never refuse — and its documentation tells an app that wants the deny to "compose that deny around this predicate rather than finding it folded in". That guidance stands; this is that composition, written once. The predicate is untouched, so nothing that calls it directly changes behaviour.

Why the deny is needed at all, and why it is not paranoia: the consumer of a loopback-only surface is an in-container CLI client, which sends none of these headers, so their presence is positive evidence the request did NOT originate inside the container. It matters because a reverse proxy SHARING the server's loopback interface (host networking, a shared network namespace) rewrites Host to its upstream address by default in both nginx and Apache — which satisfies LoopbackRequest's Host leg while the peer leg is satisfied by the proxy itself. Both legs pass and the request is remote. The provenance headers are what distinguishes it.

It has a known ceiling, stated because a gate whose limits are unwritten gets trusted past them: a same-loopback proxy that strips every provenance header is indistinguishable from an in-container caller and is admitted. Closing that needs authentication, not a header rule.

refuse writes the rejection. Pass nil for the package default (403 with the standard error envelope); pass your own to keep an envelope or wording your consumers already depend on — the refusal is the whole of what a rejected caller is told, so it belongs to the app, not here.

func NoStore

func NoStore() Middleware

NoStore returns middleware that sets Cache-Control: no-store on every response passing through it, before the next handler runs.

The value is FIXED. This is deliberately not a cache-policy API: the one header every dynamic surface needs is worth a name, and anything richer is per-asset POLICY that already has a home in WithStaticCacheControl. Three consumers had hand-written this exact three-line wrapper — for a state-reporting API, for an SPA's HTML and API responses, and for an /api/ subtree whose handlers set no cache directive at all — and the library already set the same value internally at ReadinessHandler without exporting a composable form.

PLACEMENT AND OVERRIDE ORDERING STAY APP-OWNED, exactly like WithStaticCacheControl's policy hook. The header is set before next runs and is not locked: a handler or an inner middleware that needs a different value for its own responses (a long-lived immutable asset, a per-asset cache policy, a cacheable preview image) simply Sets Cache-Control itself and wins, which is why the usual placement is innermost in the Chain — early enough to land before any handler writes a status, late enough that the asset paths that need to override it still can. Scope it by mounting it on the subtree that needs it rather than by configuring it.

It is NOT the middleware for a conditional no-store: a response that must only be uncacheable when it carries a Set-Cookie (the OWASP session- management rule) has a different trigger and a different concern, and belongs with the code that sets the cookie.

func RateLimiter

func RateLimiter(burst int, interval time.Duration, opts ...RateLimitOption) Middleware

RateLimiter returns middleware that throttles requests through a single shared token bucket (standard library only, no external dependency). burst is the maximum number of tokens and the initial fill; interval is the time to accrue one token (the refill cadence). Each admitted request consumes one token; a request that arrives with the bucket empty is answered with a 429 via WriteError(w, r, http.StatusTooManyRequests, "rate_limited", "rate limit exceeded") (code and message overridable with WithRateLimitError, the rendering with WithRateLimitResponder) and does not reach the next handler. The 429 carries a conservative Retry-After hint: the whole seconds for the CURRENT token deficit to refill at the configured rate — at most ceil(interval) when the bucket was just emptied, less when it is already partially refilled — clamped to at least 1s.

The bucket is process-wide for the middleware instance — shared across all requests and all clients — so it bounds the AGGREGATE rate of the wrapped route. That is the right tool for capping an expensive shared resource (for example, spawning a heavy child process per request), not for per-client fairness. Per-client limiting is intentionally out of scope; a caller behind a trusted proxy that needs it can key its own buckets on ClientIP.

A non-positive burst or a non-positive interval disables limiting: the middleware returns the next handler unwrapped (mirroring RouteTimeout's non-positive "off" contract), so a config-driven zero cleanly means "no limit".

Apply it to the specific handler you want to throttle, and pair it with WithRateLimitWhen to gate only the expensive method+path when the handler serves several:

sessions := webhttp.RateLimiter(6, time.Second,
	webhttp.WithRateLimitWhen(func(r *http.Request) bool {
		return r.Method == http.MethodPost
	}),
)(sessionsHandler)

func Recoverer

func Recoverer(opts ...RecoverOption) Middleware

Recoverer returns middleware that recovers a panic from a downstream handler, logs it at Error with the stack and the request id (via RequestIDFromContext), fires any WithPanicHook callback, and writes a 500 error via the configured ErrorResponder - WriteError by default, i.e. the JSON envelope {"error":"internal server error","code":"internal_error"}. Override the responder with WithRecoverResponder to render the 500 on another content type. Without it, a handler panic unwinds to net/http, which closes the connection abruptly with no response body.

The http.ErrAbortHandler sentinel is deliberately NOT recovered: per the net/http contract it is re-panicked so the server aborts the response the way the handler intended (it is not logged and fires no hook).

Placement relative to Logging matters. Put Recoverer INSIDE RequestLogger, i.e. Logging outermost, as in Chain(mux, Logging(), Recoverer()): the recovered request then records a 500 before RequestLogger's deferred access line runs, so the request logs as 500. If Recoverer sits OUTSIDE the logger, RequestLogger's deferred line runs during the panic unwind and records the StatusRecorder's default 200, a misleading access line even though the client still receives the 500.

The 500 is best-effort and never double-writes: if the handler already committed the response (wrote headers or body) before panicking, the status is on the wire and cannot be changed, so Recoverer skips the body entirely (it still logs the panic and fires the hook) rather than corrupting the partial response or mislabeling its status under an outer Logging. To detect commitment it observes the response through a StatusRecorder, reusing an existing one (such as RequestLogger's) when present.

func SecurityHeaders

func SecurityHeaders(opts ...SecurityOption) Middleware

SecurityHeaders returns middleware that sets a baseline of response security headers before calling the next handler. Set by default are X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and Referrer-Policy: strict-origin-when-cross-origin. The X-Frame-Options and Referrer-Policy defaults are configurable (override with a value, or omit with an empty string); nosniff is set by default with no option to change it here. Content-Security-Policy, Permissions-Policy, Cross-Origin-Opener-Policy, and Strict-Transport-Security are off unless their options are supplied.

All of these are set BEFORE next runs, so none is immutable: the middleware establishes the baseline but does not lock it. A handler that needs a different value for a specific response can still override (or delete) any of them, nosniff included, on the response header.

func SessionCreateRateLimit

func SessionCreateRateLimit(path string) Middleware

SessionCreateRateLimit returns middleware gating POST requests to path (an exact match, e.g. "/api/sessions") behind the standard session-create token bucket: burst 6, one token accrued per second, and a 429 envelope of code "rate_limited" / message "session creation rate exceeded". Non-POST methods and other paths pass through without consuming a token, so a handler that multiplexes list (GET) and close (DELETE) on the same path stays unthrottled.

This is a preset over RateLimiter for the create-a-heavy-child endpoint shape, where each admitted request forks an expensive process (a PTY, an agent subprocess) and what needs bounding is aggregate create churn. The tuning lives here once; an app needing different numbers or a different predicate composes RateLimiter directly.

type RateLimitOption

type RateLimitOption func(*rateLimitConfig)

RateLimitOption configures RateLimiter.

func WithRateLimitError

func WithRateLimitError(code ErrorCode, msg string) RateLimitOption

WithRateLimitError sets the error code and message written in the 429 JSON envelope (via WriteError). Defaults to "rate_limited" / "rate limit exceeded".

code is the machine token and msg the sentence; they are separately typed (see ErrorCode) so the pair cannot be supplied transposed. An empty code omits the field.

func WithRateLimitResponder

func WithRateLimitResponder(fn ErrorResponder) RateLimitOption

WithRateLimitResponder sets the ErrorResponder that writes the 429 body when a request is denied. It defaults to WriteError - the JSON envelope; supply one to render the 429 on a different content type, for example an XML endpoint returning its own error document. The responder owns writing the status and headers (the Retry-After hint is already set on w when it runs). A nil responder is ignored, keeping the default.

It composes with WithRateLimitError rather than replacing it: the code and message that option sets are the ones handed to the responder, so an app keeps one error taxonomy across both renderings.

func WithRateLimitWhen

func WithRateLimitWhen(pred func(*http.Request) bool) RateLimitOption

WithRateLimitWhen restricts limiting to requests for which pred returns true; every other request passes through without consuming a token. Use it to gate a single method+path on a handler that multiplexes several — for example, throttle only POST and leave GET/DELETE on the same path unthrottled. A nil predicate is ignored, so the default (limit every request) stands.

type ReadinessChecker

type ReadinessChecker interface {
	// Ready reports whether the service should receive traffic right now.
	Ready() bool
}

ReadinessChecker is the readiness view ReadinessHandler needs. *Ready satisfies it; a service with a composite readiness model can supply its own implementation.

type Ready

type Ready struct {
	// contains filtered or unexported fields
}

Ready is a concurrency-safe readiness flag. Its zero value reports not ready, so a service starts unready until it calls Set(true) once initialization completes, and can flip back to unready during shutdown.

func (*Ready) Ready

func (r *Ready) Ready() bool

Ready reports whether the service is currently ready to serve traffic.

func (*Ready) Set

func (r *Ready) Set(ready bool)

Set records whether the service is ready to serve traffic.

type RecoverOption

type RecoverOption func(*recoverConfig)

RecoverOption configures Recoverer.

func WithPanicHook

func WithPanicHook(fn func(v any, stack []byte)) RecoverOption

WithPanicHook registers a callback invoked with the recovered value and the captured stack when a panic is caught. Use it to increment a metric or notify an error tracker. It runs after the panic is logged and before the 500 response is written; a nil hook is ignored.

func WithRecoverLogger

func WithRecoverLogger(l *slog.Logger) RecoverOption

WithRecoverLogger sets the slog.Logger used to report a recovered panic. Defaults to slog.Default().

func WithRecoverResponder

func WithRecoverResponder(fn ErrorResponder) RecoverOption

WithRecoverResponder sets the ErrorResponder that writes the 500 body after a recovered panic (only when the response is not already committed). It defaults to WriteError - the JSON envelope; supply one to render the 500 on a different content type, for example an XML endpoint returning its own error document. The responder owns writing the status and headers. A nil responder is ignored, keeping the default.

type RequestMetric

type RequestMetric struct {
	// Method is the request method, bounded by the hook that produced it.
	Method string
	// Path is the label the hook chose: a bounded request path for
	// [WithRecordMetric], or the matched route template for
	// [WithRecordRouteMetric] (MetricLabelUnmatched when nothing matched).
	Path string
	// Status is the response status actually written.
	Status int
	// Latency is how long the handler took.
	Latency time.Duration
}

RequestMetric is one completed request as a metric hook observes it: the labels and the latency, already bounded by whichever hook produced it.

It is a struct rather than four parameters because two of them are adjacent strings: a hook implemented as func(path, method string, ...) compiles, runs forever, and silently labels every series with the wrong dimension — and nothing in a metric can look wrong afterwards, since both values are plausible strings. Named fields make the implementor read Method and Path instead of counting positions. The stdlib passes multi-value hook data the same way: net/http/httptrace's GotConn and DNSDone take GotConnInfo and DNSDoneInfo rather than positional arguments.

type RunOption

type RunOption func(*runConfig)

RunOption configures Run.

func WithPreDrain

func WithPreDrain(fn func(ctx context.Context)) RunOption

WithPreDrain registers a hook Run invokes after ctx is cancelled and strictly before srv.Shutdown starts draining in-flight requests. It is the place for the release-the-streams phase a graceful stop needs ahead of the drain: flip a readiness gate so a load balancer stops routing here, cancel the server's BaseContext or shut down an SSE hub so long-lived connections end (otherwise Shutdown waits its full grace period for them). fn receives a context bounded by the SAME shutdown deadline that Shutdown and onShutdown share; whatever budget it spends is no longer available to them. A nil fn is ignored.

func WithServeExit

func WithServeExit(fn func(ctx context.Context)) RunOption

WithServeExit registers an opt-in teardown hook Run invokes when srv.Serve returns on its own — before ctx is ever cancelled — in place of the graceful sequence. That covers a fatal serve error (the listener or the accept loop is gone) and a Shutdown or Close the caller drove itself outside Run. Exactly one of the two paths runs per Run call: with the hook registered, either pre-drain -> Shutdown -> onShutdown ran, or fn did. Without it, Run keeps today's behavior of returning the serve error with NEITHER hook invoked, so an existing caller sees no change. A nil fn is ignored.

fn receives a context bounded by the shutdown grace period, and gets the whole budget: there was no drain to share it with. Run does NOT call srv.Shutdown on this path — Serve has already returned and closed the listener, so a drain would only spend fn's budget waiting on connections whose accept loop is already dead.

WithPreDrain and onShutdown are NOT reused here, because both are documented against a graceful stop that this path is not: ctx is still LIVE (nothing cancelled it), and there is no drain for a pre-drain phase to precede. That matters for what fn must do — a teardown that waits on a goroutine keyed to ctx (a background loop stopped by the same signal context) has to cancel it inside fn, by calling the signal context's stop function, or it waits out the whole grace for a goroutine nothing has asked to stop. A caller whose teardown is cancellation-independent can pass the same function to both slots: Run(ctx, srv, ln, teardown, WithServeExit(teardown)).

func WithShutdownGrace

func WithShutdownGrace(d time.Duration) RunOption

WithShutdownGrace sets how long Run allows for graceful shutdown: the window for the pre-drain hook to run, for in-flight requests to finish, and for the onShutdown teardown to run. Defaults to 5s.

type SecurityOption

type SecurityOption func(*securityConfig)

SecurityOption configures SecurityHeaders.

func WithCOOP

func WithCOOP(v string) SecurityOption

WithCOOP sets the Cross-Origin-Opener-Policy header (e.g. "same-origin"). Unset by default.

func WithCSP

func WithCSP(policy string) SecurityOption

WithCSP sets the Content-Security-Policy header. The library never builds a policy for you: a CSP is application-specific (it must match the app's script and style sources, nonces, or hashes), so pass the exact policy string the app needs. Unset by default.

func WithFrameOptions

func WithFrameOptions(v string) SecurityOption

WithFrameOptions overrides the X-Frame-Options header (default "DENY"). Pass an empty string to omit the header, for example when a Content-Security-Policy frame-ancestors directive supersedes it.

func WithHSTS

func WithHSTS(policy HSTS) SecurityOption

WithHSTS enables the Strict-Transport-Security header from the given policy. HSTS is OFF by default: enable it only for a service reached exclusively over HTTPS, because a browser that sees the header will refuse plain-HTTP and untrusted-certificate connections to the host for the whole max-age window.

webhttp.SecurityHeaders(webhttp.WithHSTS(webhttp.HSTS{
	MaxAge:            365 * 24 * time.Hour,
	IncludeSubdomains: true,
	Preload:           true,
}))

A policy asking for Preload WITHOUT IncludeSubdomains is REFUSED, not repaired: the header is emitted without the preload directive, and the contradiction is logged at Warn naming the field to set (once per WithHSTS call, which is wiring time rather than a request path). That is the honest rendering — the browsers' preload list rejects such a submission (hstspreload.org), so a header carrying the directive would advertise a posture the operator does not actually get, and the failure would surface only at submission time.

The two rejected alternatives are worth recording. PANICKING is wrong for a value that can legitimately come from configuration; the library's answer for a caller that wants to fail closed at startup is HSTS.Validate, which returns the same verdict as an error. And SILENTLY SETTING IncludeSubdomains would widen a security policy the caller did not ask for: HSTS on every subdomain is a strictly larger commitment than HSTS on one host, and inferring it from a neighbouring flag is exactly the kind of repair CanonicalHost refuses for the same reason.

func WithPermissionsPolicy

func WithPermissionsPolicy(v string) SecurityOption

WithPermissionsPolicy sets the Permissions-Policy header (browser feature gating, e.g. "geolocation=(), camera=()"). Unset by default.

func WithReferrerPolicy

func WithReferrerPolicy(v string) SecurityOption

WithReferrerPolicy overrides the Referrer-Policy header (default "strict-origin-when-cross-origin"). Pass an empty string to omit it.

type ServerOption

type ServerOption func(*http.Server)

ServerOption configures the *http.Server built by NewServer.

func WithErrorLog

func WithErrorLog(l *log.Logger) ServerOption

WithErrorLog sets http.Server.ErrorLog so connection-level errors go to the caller's logger instead of the standard logger. It is the override for a custom *log.Logger; for the ordinary case of routing those lines into slog at a chosen level, use WithSlogErrorLog.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) ServerOption

WithIdleTimeout sets http.Server.IdleTimeout, the keep-alive idle deadline.

func WithMaxHeaderBytes

func WithMaxHeaderBytes(n int) ServerOption

WithMaxHeaderBytes sets http.Server.MaxHeaderBytes.

func WithReadHeaderTimeout

func WithReadHeaderTimeout(d time.Duration) ServerOption

WithReadHeaderTimeout sets http.Server.ReadHeaderTimeout, the slowloris guard bounding how long a client may take to send request headers.

func WithReadTimeout

func WithReadTimeout(d time.Duration) ServerOption

WithReadTimeout sets http.Server.ReadTimeout, the deadline for reading the entire request. Leave it unset for streaming request bodies.

func WithSlogErrorLog

func WithSlogErrorLog(level slog.Level) ServerOption

WithSlogErrorLog sets http.Server.ErrorLog to a bridge that forwards net/http's own connection-level lines into slog at level, so they arrive as level-carrying records in an otherwise structured stream instead of as unstructured, level-less standard-logger output that no level-based log rule can match. The lines it covers are net/http's, above all "http: Accept error: ...; retrying" — the trace of an exhausted fd budget, which is a whole-service outage no request-scoped log will report.

The LEVEL is the caller's policy and deliberately has no default here, because consumers legitimately disagree: an accept failure is fatal to a service whose only job is to answer probes (Error) and a degradation to one that will retry (Warn). This option only gives that choice a named home instead of three hand-written copies of the same slog.NewLogLogger recipe.

It resolves slog.Default() when the option is APPLIED (inside NewServer), so install the process logger before building the server; a later slog.SetDefault does not retroactively re-target an already-built http.Server. WithErrorLog remains the escape hatch for any other *log.Logger, and the default (net/http's standard logger) is unchanged when neither option is passed.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) ServerOption

WithWriteTimeout sets http.Server.WriteTimeout, the deadline for writing the entire response. It is unset by default: streaming apps (SSE, WebSocket, long responses) MUST omit it, because it would cut off an in-progress stream.

type StaticOption

type StaticOption func(*staticConfig)

StaticOption configures StaticHandler.

func WithStaticCacheControl

func WithStaticCacheControl(fn func(assetPath string) string) StaticOption

WithStaticCacheControl sets the per-asset Cache-Control policy, "no-cache" for every asset by default. fn receives the asset path with no leading slash, "index.html" for "/", and returns the header value; an empty value omits the header. It chooses the value only: ETags, gzip and revalidation are fixed. A nil fn keeps the default.

type StaticTokenVerifier

type StaticTokenVerifier struct {
	// contains filtered or unexported fields
}

StaticTokenVerifier verifies presented credentials against the single operator-configured secret guarding an endpoint. It is the constant-time verification primitive for static machine credentials — an API key, a bearer token, a basic-auth user or password — where exactly one expected value comes from configuration. It verifies one shared secret, not user identities: per-user credential stores, password hashing, and session management belong to the auth library (github.com/cplieger/auth), not here.

Construct it once with NewStaticTokenVerifier and reuse it for every request. The configured secret is hashed with SHA-256 at construction; Verify hashes only the presented value and compares the two fixed-length digests with subtle.ConstantTimeCompare. Comparing 32-byte digests rather than the raw strings removes ConstantTimeCompare's unequal-length short-circuit (CWE-208), and pre-hashing the configured secret means no per-call timing varies with the secret's length or content — hashing the presented value per call reveals only what the caller already knows: its own input.

The zero value fails CLOSED: Verify returns false for every presented value until the verifier is constructed from a non-empty secret.

func NewStaticTokenVerifier

func NewStaticTokenVerifier(configured string) StaticTokenVerifier

NewStaticTokenVerifier builds a verifier for the configured secret.

An empty configured secret yields the zero verifier, which fails CLOSED: Verify returns false for every presented value, including the empty string. Without that guard the digest comparison would fail OPEN — sha256("") equals sha256(""), so an unset secret would grant access to any client that simply presents no credential. Treat an empty configured value as "auth not configured", never as "no credential required": a caller that wants an open endpoint should skip the gate explicitly rather than rely on an empty secret.

Example
package main

import (
	"fmt"

	"github.com/cplieger/webhttp/v4"
)

func main() {
	v := webhttp.NewStaticTokenVerifier("s3cr3t")
	fmt.Println(v.Verify("s3cr3t"))
	fmt.Println(v.Verify("wrong"))
	// An unset secret fails closed: even an empty presented value is rejected.
	unset := webhttp.NewStaticTokenVerifier("")
	fmt.Println(unset.Verify(""))
}
Output:
true
false
false

func (StaticTokenVerifier) Verify

func (v StaticTokenVerifier) Verify(presented string) bool

Verify reports whether presented matches the configured secret. It is safe for concurrent use.

type StatusRecorder

type StatusRecorder struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

StatusRecorder wraps an http.ResponseWriter to record the response status for middleware such as access logging and metrics.

It implements http.Flusher, FlushError, http.Hijacker and io.ReaderFrom itself, each returning the underlying writer's result (a passed write deadline, http.ErrNotSupported on an HTTP/2 hijack), so type assertions, http.NewResponseController and the sendfile fast path work through it. Unwrap reaches the rest of the underlying writer, such as its deadlines.

func NewStatusRecorder

func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder

NewStatusRecorder wraps w. The recorded status defaults to http.StatusOK (200) and stays there until WriteHeader or the first Write records a status.

func (*StatusRecorder) Flush

func (s *StatusRecorder) Flush()

Flush is FlushError for callers that type-assert http.Flusher, which has no way to report the error.

func (*StatusRecorder) FlushError added in v4.1.0

func (s *StatusRecorder) FlushError() error

FlushError flushes the underlying writer through http.ResponseController and returns its error: http.ErrNotSupported when no writer below could flush, or the connection's own failure, such as os.ErrDeadlineExceeded. Any other result commits the response, because net/http latches its implicit 200 before it flushes. A wrapper that writes before reporting http.ErrNotSupported is not seen as committed, which is why Gzip belongs inside Recoverer.

func (*StatusRecorder) Hijack

func (s *StatusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack forwards to the underlying writer via http.ResponseController for libraries that hijack the connection through a direct http.Hijacker assertion. Returns an error (e.g. http.ErrNotSupported) when the underlying writer, such as an HTTP/2 stream, cannot be hijacked.

func (*StatusRecorder) ReadFrom

func (s *StatusRecorder) ReadFrom(src io.Reader) (int64, error)

ReadFrom preserves the zero-copy (sendfile) fast path for io.Copy and http.ServeContent when the underlying writer implements io.ReaderFrom. Writing the body implies a 200 status when WriteHeader was not called.

func (*StatusRecorder) Status

func (s *StatusRecorder) Status() int

Status returns the recorded status code, or http.StatusOK if none was set.

func (*StatusRecorder) Unwrap

func (s *StatusRecorder) Unwrap() http.ResponseWriter

Unwrap returns the wrapped http.ResponseWriter, so http.NewResponseController reaches the optional methods the recorder does not implement itself, such as SetWriteDeadline and EnableFullDuplex.

func (*StatusRecorder) Write

func (s *StatusRecorder) Write(b []byte) (int, error)

Write records an implicit 200 status on the first write when WriteHeader was not called (mirroring net/http), then forwards to the wrapped writer.

func (*StatusRecorder) WriteHeader

func (s *StatusRecorder) WriteHeader(code int)

WriteHeader records the first explicit status code and forwards every call to the wrapped writer. Only the first code is recorded, matching net/http's first-code-wins semantics; a later call still forwards (so net/http logs its standard "superfluous WriteHeader" warning) but does not change Status.

func (*StatusRecorder) Wrote

func (s *StatusRecorder) Wrote() bool

Wrote reports whether the response has been committed, i.e. WriteHeader, the first Write or ReadFrom, a Flush that returned anything but http.ErrNotSupported (a failed flush included), or a successful Hijack has run. Middleware such as Recoverer consults it to avoid writing a second status and body onto a response a handler has already started, which would corrupt the body and mislabel the status.

Jump to

Keyboard shortcuts

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