Documentation
¶
Overview ¶
Package httpserver is server-side HTTP plumbing on top of net/http: request-id and bounded access logging (Logging), a transparent StatusRecorder, composable middleware (Chain, Recoverer, SecurityHeaders, Gzip, RouteTimeout, RouteDeadline, RateLimiter and its FailedAuthRateLimit preset, NoStore, LoopbackOnly), 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 graceful server (New, Run) and an opt-in metrics listener (ListenMetrics).
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 ¶
- Constants
- Variables
- func AwaitDone(ctx context.Context, done <-chan struct{}) bool
- func CanonicalHost(hostport string) string
- func CanonicalRequestPath(p string) (clean string, canonical bool)
- func CausedByCancellation(ctx context.Context, err error) bool
- func Chain(h http.Handler, mw ...Middleware) http.Handler
- func ClientIP(r *http.Request, trusted ...netip.Prefix) string
- func DecodeBody(w http.ResponseWriter, r *http.Request, v any, errMsg string) bool
- func DecodeJSONInto(w http.ResponseWriter, r *http.Request, v any, maxBytes int64) error
- func InlineScriptHashes(html []byte) []string
- func InlineStyleHashes(html []byte) []string
- func JSONHeaders(w http.ResponseWriter)
- func LimitBody(w http.ResponseWriter, r *http.Request, maxBytes int64)
- func LoopbackRequest(r *http.Request) bool
- func MethodNotAllowed(w http.ResponseWriter, r *http.Request, allowed ...string)
- func New(handler http.Handler, opts ...ServerOption) *http.Server
- func NewRequestID() string
- func OK(w http.ResponseWriter)
- func ParseCIDRs(entries []string) (prefixes []netip.Prefix, invalid []string)
- func ProxiedRequest(h http.Header) bool
- func RequestIDFromContext(ctx context.Context) string
- func RequireMethod(w http.ResponseWriter, r *http.Request, method string) bool
- func RouteDeadline(h http.Handler, d time.Duration) http.Handler
- func RouteTimeout(h http.Handler, d time.Duration, msg string) http.Handler
- func Run(ctx context.Context, srv *http.Server, ln net.Listener, opts ...RunOption) error
- func SetAllow(w http.ResponseWriter, allowed ...string)
- func StaticHandler(fsys fs.FS, opts ...StaticOption) (http.Handler, error)
- func ValidRequestID(s string) bool
- func WithRequestID(ctx context.Context, id string) context.Context
- func WriteError(w http.ResponseWriter, r *http.Request, status int, code ErrorCode, msg string)
- func WriteJSON(w http.ResponseWriter, v any)
- func WriteJSONStatus(w http.ResponseWriter, status int, v any)
- type BindClass
- type ClientResolution
- type ErrorCode
- type ErrorResponder
- type ErrorResponse
- type GzipOption
- type HSTS
- type HostAllowlistOption
- type HostPolicy
- type LogOption
- func WithClientIP(trusted ...netip.Prefix) LogOption
- func WithClientIPFunc(fn func(*http.Request) string) LogOption
- func WithLogLevel(fn func(r *http.Request, status int) slog.Level) LogOption
- func WithLogger(l *slog.Logger) LogOption
- func WithMaxLoggedPath(n int) LogOption
- func WithPathFunc(fn func(*http.Request) string) LogOption
- func WithProbeLogLevel(paths ...string) LogOption
- func WithRecordRouteMetric(fn func(RequestMetric)) LogOption
- func WithSkipFunc(fn func(*http.Request) bool) LogOption
- func WithSkipPaths(paths ...string) LogOption
- func WithSkipUpgrades(skip bool) LogOption
- func WithTemplatePathsUnder(prefixes ...string) LogOption
- type LoopbackOption
- type MetricsHandlers
- type MetricsServer
- type Middleware
- func FailedAuthRateLimit(when func(*http.Request) bool, msg string, opts ...RateLimitOption) Middleware
- func Gzip(opts ...GzipOption) Middleware
- func Logging(opts ...LogOption) Middleware
- func LoopbackOnly(opts ...LoopbackOption) Middleware
- func NoStore() Middleware
- func RateLimiter(burst int, interval time.Duration, opts ...RateLimitOption) Middleware
- func Recoverer(opts ...RecoverOption) Middleware
- func SecurityHeaders(opts ...SecurityOption) Middleware
- type RateLimitOption
- type RecoverOption
- type RequestMetric
- type RunOption
- type SecurityOption
- type ServerOption
- type StaticOption
- type StaticTokenVerifier
- type StatusRecorder
- func (s *StatusRecorder) Flush()
- func (s *StatusRecorder) FlushError() error
- func (s *StatusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (s *StatusRecorder) ReadFrom(src io.Reader) (int64, error)
- func (s *StatusRecorder) Status() int
- func (s *StatusRecorder) Unwrap() http.ResponseWriter
- func (s *StatusRecorder) Write(b []byte) (int, error)
- func (s *StatusRecorder) WriteHeader(code int)
- func (s *StatusRecorder) Wrote() bool
Examples ¶
Constants ¶
const HeaderRequestID = "X-Request-ID"
HeaderRequestID is the canonical request-id header. Logging reads it from the inbound request and echoes it on the response.
const MaxJSONBody int64 = 1 << 20
MaxJSONBody is the default maximum JSON request-body size (1 MiB) applied by DecodeBody.
Variables ¶
var ( ErrHSTSPreloadWithoutSubdomains = errors.New("httpserver: HSTS preload requires IncludeSubdomains") ErrHSTSPreloadMaxAgeTooShort = errors.New("httpserver: 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.
var ErrShutdownGraceExpired = errors.New("httpserver: 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, httpserver.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.
var ErrTrailingData = errors.New("httpserver: 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 ¶
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 the WithTeardown hook 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 ¶
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 ¶
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 ¶
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 := httpserver.Chain(mux, httpserver.Logging(), // outermost: logs every request httpserver.Recoverer(), // catches panics from everything below it httpserver.SecurityHeaders(), // sets headers before the app runs )
A nil middleware in the list is skipped, so callers can include entries conditionally.
func ClientIP ¶
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 ¶
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 DecodeJSONInto ¶
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 httpserver consumers) build their own one-liner on it instead of reproducing the cap + decode + trailing-check by hand.
func InlineScriptHashes ¶
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 ¶
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:
httpserver.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 ¶
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) {
httpserver.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/go/httpserver"
)
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.
httpserver.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 New ¶
func New(handler http.Handler, opts ...ServerOption) *http.Server
New 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. Assign a field of the returned server to change a default.
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 set srv.ReadTimeout to bound slowloris-style slow bodies; WriteTimeout must stay unset for a streaming one, because it would cut off an in-progress stream. 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 ¶
New returns the *http.Server, so every field 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, which is why WithSlogErrorLog, which builds a bridge, is the one ServerOption. Three fields 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 httpserver'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 New 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 New 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 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 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/go/httpserver"
)
func main() {
rr := httptest.NewRecorder()
httpserver.OK(rr)
fmt.Print(rr.Body.String())
}
Output: {"ok":true}
func ParseCIDRs ¶
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 ¶
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 RequestIDFromContext ¶
RequestIDFromContext returns the request id stored in ctx by WithRequestID, or "" if none is present.
func RequireMethod ¶
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 !httpserver.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 RouteDeadline ¶
RouteDeadline gives h's request context a deadline d and runs h on the request's own goroutine. It writes no status of its own, so h must write the one its outcome calls for (net/http answers 200 if h writes nothing): the choice over RouteTimeout for a handler that changes state. A call that watches the context returns at the deadline; nothing else ends at d, so the client can wait past it, and h must check the context before committing. A non-positive d returns h unwrapped. docs/middleware.md has the full contract.
func RouteTimeout ¶
RouteTimeout answers 503 with a JSON ErrorResponse (code "timeout", msg or "request timed out", and the request id when the context has one) once h has run longer than d; a non-positive d returns h unwrapped. It does not stop h: h keeps running with its request context cancelled and can still commit after the 503, so never wrap a handler that changes state; use RouteDeadline for that one. It buffers the whole response, so it cannot wrap a streaming or hijacking handler, and it labels any 503 without a Content-Type as JSON. docs/middleware.md in the module has the full contract.
func Run ¶
Run serves srv on ln until ctx is cancelled, then shuts down within one grace period (WithShutdownGrace): the WithPreDrain hook, srv.Shutdown, then the WithTeardown hook, 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. srv and ln must be non-nil; Run panics on either before serving.
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 ¶
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 ¶
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/go/httpserver"
)
func main() {
fmt.Println(httpserver.ValidRequestID("abc-123_XYZ"))
fmt.Println(httpserver.ValidRequestID("bad id"))
}
Output: true false
func WithRequestID ¶
WithRequestID returns a copy of ctx carrying the request id.
func WriteError ¶
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/go/httpserver"
)
func main() {
rr := httptest.NewRecorder()
// r may be nil; the request_id field is then omitted.
httpserver.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, status 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 ¶
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 httpserver.ClassifyBind(addr) == httpserver.BindExposed { warn(...) }
// Fail-public (pg-autodump): a spurious warning is preferable to a
// silently unflagged open endpoint.
if httpserver.ClassifyBind(addr) != httpserver.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 := httpserver.ClassifyBind(addr)
if class == httpserver.BindInvalid { class = httpserver.ClassifyBindHost(addr) }
if class != httpserver.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 ¶
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.
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 unless zoned; the zero Addr
// when it is not an IP address.
Peer netip.Addr
// PeerTrusted reports that Peer is inside the trusted set, whether or not
// it forwarded a client, so a caller that reads a trusted proxy's other
// headers (X-Forwarded-Proto, say) asks the same rule. Forwarded implies
// it, and UntrustedForwarding excludes it.
PeerTrusted bool
// 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 ¶
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 WithHostAllowlistLogger ¶
func WithHostAllowlistLogger(l *slog.Logger) HostAllowlistOption
WithHostAllowlistLogger sets the slog.Logger that Middleware and LogRefusal report each refusal to. Nil, the default, means slog.Default() as it is when ParseHostList runs. Pass a logger with a discarding handler to silence it.
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) LogRefusal ¶ added in v1.2.0
func (p *HostPolicy) LogRefusal(r *http.Request)
LogRefusal writes the Warn line Middleware writes for a refused Host, for a caller that admits by its own rule and writes its own refusal. It logs through the policy's logger (WithHostAllowlistLogger) with its hint (WithHostAllowlistError); a nil or zero-value policy uses slog.Default and the default hint. The line carries no path, which can hold a token; the access line with the same request_id has it. The Host is empty when the request named none: HTTP/1.0 or HTTP/2 without one, or an empty Host header.
func (*HostPolicy) Middleware ¶
func (p *HostPolicy) Middleware() Middleware
Middleware returns the allowlist as httpserver middleware. An inactive or nil policy returns the next handler unwrapped, the "off" contract RateLimiter and RouteTimeout share. An active policy answers a disallowed Host with a 403 via WriteError (see WithHostAllowlistError) before the next handler runs, and logs one Warn with the reason, host, remote, hint and, when the context has one, request_id (see WithHostAllowlistLogger). Put it outermost among request-authorization middleware: a DNS-rebinding request makes Origin and Host agree, so only the exact-Host check breaks it (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 Logging.
func WithClientIP ¶
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 ¶
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 WithRecordRouteMetric. 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 ¶
WithLogLevel sets the access line's level: fn gets the request and the final status, and the line is emitted at the level it returns (Info without this option). WithProbeLogLevel is the preset for probe paths; a split by status (2xx and 3xx at Debug, 4xx at Warn, 5xx at Error) suits routes a person requests, where each 4xx or 5xx is one event. A skipped request never calls fn, a panicking fn is logged and the line falls back to Info, and a nil fn is ignored.
func WithLogger ¶
WithLogger sets the slog.Logger used for access-log lines. Defaults to slog.Default().
func WithMaxLoggedPath ¶
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 ¶
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 and the "path" attribute of the package's hook-failure diagnostics. It does not feed WithRecordRouteMetric, whose path label is the matched route, 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. Middleware between Logging 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 WithProbeLogLevel ¶
WithProbeLogLevel is the 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 whatever its status, since a probe repeats one standing state; every other request stays at Info. It is a WithLogLevel policy, so the last of the two applied wins. A skipped path never consults it, a panicking policy falls back to Info, and with no paths every request logs at Info.
func WithRecordRouteMetric ¶
func WithRecordRouteMetric(fn func(RequestMetric)) LogOption
WithRecordRouteMetric registers the per-request metric hook: fn is invoked once per logged request with a RequestMetric whose method and path labels THIS PACKAGE derives, 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; safety is a property of the wiring, not of every consumer remembering to bound its labels.
The labels are bounded BY CONSTRUCTION, so cardinality is a function of the route table, not of the traffic. 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.
- Method is r.Method when it is one of the nine standard methods (GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE from RFC 9110 §9.3, and PATCH from RFC 5789) and the fixed "other" bucket for everything else: ten values whatever arrives on the request line. Methods are case-sensitive, so "get" is "other".
- Path is the route http.ServeMux matched: r.Pattern with its method prefix stripped ("GET /beat/{id}" records "/beat/{id}", so every id records as one series), the pattern itself when it names no method, and the fixed "unmatched" marker when nothing matched (r.Pattern == "", as for net/http's own 404 and 405). A host-qualified pattern keeps its host.
Every value is therefore a pattern the SERVER registered or one of the ten method labels or the "unmatched" path marker, so the series ceiling is ten times one more than the route table. The method comes from the request, bounded by the closed set, rather than from the matched pattern, so a HEAD probe against a GET-only pattern records HEAD as its access line does. The one deliberate divergence from the access line: a non-standard method is recorded verbatim there (bounded to 24 bytes) and as "other" here; the access line for the same request_id says what it was.
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). 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 one.
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. Middleware between Logging 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, so every request reads as "unmatched": check that before believing a flat metric.
Example ¶
package main
import (
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/cplieger/go/httpserver"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /beat/{id}", func(http.ResponseWriter, *http.Request) {})
h := httpserver.Logging(
httpserver.WithLogger(slog.New(slog.DiscardHandler)),
httpserver.WithRecordRouteMetric(func(m httpserver.RequestMetric) {
fmt.Println(m.Method, m.Path, m.Status)
}),
)(mux)
// A HEAD probe records HEAD, not the pattern's GET, so the metric and the
// access line agree on the method; every id records as one series.
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodHead, "/beat/7", nil))
// 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.
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("PROPFIND", "/beat/7", nil))
// Nothing matched: every unrouted request shares one path label.
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/nope", nil))
}
Output: HEAD /beat/{id} 200 other unmatched 405 GET unmatched 404
func WithSkipFunc ¶
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 ¶
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 ¶
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 WithProbeLogLevel 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 ¶
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 LoopbackOption ¶
type LoopbackOption func(*loopbackConfig)
LoopbackOption configures LoopbackOnly.
func WithLoopbackError ¶
func WithLoopbackError(code ErrorCode, msg string) LoopbackOption
WithLoopbackError sets the code and message of LoopbackOnly's 403. 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 WithLoopbackResponder ¶
func WithLoopbackResponder(fn ErrorResponder) LoopbackOption
WithLoopbackResponder sets the ErrorResponder that writes LoopbackOnly's 403, in place of WriteError's JSON envelope; it receives the status, code and message, so it composes with WithLoopbackError. A responder is also the place to log a refusal. A nil fn is ignored, keeping the default.
type MetricsHandlers ¶ added in v1.2.0
type MetricsHandlers struct {
// Metrics answers GET /metrics.
Metrics http.Handler
// Healthz answers GET /healthz.
Healthz http.Handler
}
MetricsHandlers names the two handlers the metrics listener serves, so they cannot be passed in each other's place.
type MetricsServer ¶ added in v1.2.0
type MetricsServer struct {
// contains filtered or unexported fields
}
MetricsServer is the opt-in listener of an app that opens no port of its own: it routes only /metrics and /healthz, for GET and the HEAD a GET pattern matches, both under WithProbeLogLevel, with panics recovered. Build it with ListenMetrics, which binds before the app starts work, then call Serve.
func ListenMetrics ¶ added in v1.2.0
func ListenMetrics(ctx context.Context, addr string, h MetricsHandlers, opts ...ServerOption) (*MetricsServer, error)
ListenMetrics binds addr, a net.Listen "tcp" address, before it returns and serves h once Serve runs. A bind failure is returned naming addr. An empty addr opens nothing: Serve then returns nil at once and Addr is nil. ListenMetrics reads no environment, and opts reach New. It panics on a nil handler, whatever addr is, so the mistake shows with the listener off too.
Example ¶
An app with no port of its own serves an opt-in metrics and health listener. ListenMetrics binds first, so a port in use fails before any work starts.
package main
import (
"context"
"fmt"
"io"
"net/http"
"github.com/cplieger/go/httpserver"
)
func main() {
metrics := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, "app_up 1\n")
})
healthz := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, `{"status":"ok"}`)
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ms, err := httpserver.ListenMetrics(ctx, "127.0.0.1:0", httpserver.MetricsHandlers{Metrics: metrics, Healthz: healthz})
if err != nil {
fmt.Println("refusing to start:", err)
return
}
done := make(chan error, 1)
go func() { done <- ms.Serve(ctx) }()
for _, path := range []string{"/metrics", "/healthz", "/api"} {
resp, err := http.Get("http://" + ms.Addr().String() + path)
if err != nil {
fmt.Println(err)
continue
}
_ = resp.Body.Close()
fmt.Println(path, resp.StatusCode)
}
cancel()
fmt.Println("stopped:", <-done)
}
Output: /metrics 200 /healthz 200 /api 404 stopped: <nil>
func (*MetricsServer) Addr ¶ added in v1.2.0
func (m *MetricsServer) Addr() net.Addr
Addr returns the bound address, which names the port the kernel chose for a ":0" address, or nil when the listener is off.
func (*MetricsServer) Close ¶ added in v1.2.0
func (m *MetricsServer) Close() error
Close releases a listener Serve has not started, for a caller that gives up before serving, such as a startup that fails after ListenMetrics. Once Serve has started it does nothing and returns an error: cancel Serve's context to stop the server. It returns nil when the listener is off, and for a repeated Close.
func (*MetricsServer) Serve ¶ added in v1.2.0
func (m *MetricsServer) Serve(ctx context.Context, opts ...RunOption) error
Serve serves until ctx is cancelled, then shuts down as Run does with opts, and returns Run's error. When the listener is off it returns nil at once. A call after Serve or Close, on a listener that is on, returns an error and serves nothing.
type Middleware ¶
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, opts ...RateLimitOption) 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.
opts apply after the preset's own, so WithRateLimitResponder renders the 429 on another content type; a non-nil WithRateLimitWhen or a WithRateLimitError in opts replaces the preset's predicate or envelope.
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/go/httpserver"
)
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 := httpserver.Chain(api, httpserver.Recoverer(), httpserver.Gzip(httpserver.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 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 LoopbackOnly ¶
func LoopbackOnly(opts ...LoopbackOption) 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.
A refused request is answered 403 through WriteError with the code "loopback_only" and a message telling the caller to call from inside the container. WithLoopbackError replaces the code and message and WithLoopbackResponder the renderer, as WithRateLimitError and WithRateLimitResponder do for RateLimiter: the refusal is the whole of what a rejected caller is told, so its wording belongs to the app.
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.
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 := httpserver.RateLimiter(6, time.Second,
httpserver.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 Logging, i.e. Logging outermost, as in Chain(mux, Logging(), Recoverer()): the recovered request then records a 500 before Logging's deferred access line runs, so the request logs as 500. If Recoverer sits OUTSIDE the logger, Logging'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 Logging'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.
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 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 one of the nine standard methods, or "other" for any other.
Method string
// Path is the matched route template, or the fixed "unmatched" marker
// 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 ¶
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 WithTeardown share; whatever budget it spends is no longer available to them. A nil fn is ignored.
func WithServeExit ¶
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 -> teardown 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 WithTeardown 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: Run(ctx, srv, ln, WithTeardown(teardown), WithServeExit(teardown)).
func WithShutdownGrace ¶
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 WithTeardown hook to run. Defaults to 5s.
func WithTeardown ¶
WithTeardown registers the hook Run invokes after srv.Shutdown has drained in-flight requests, on the graceful path only: the place to close what the handlers used (a store, a hub, a background loop). fn receives a context bounded by the same shutdown deadline as WithPreDrain and Shutdown. A nil fn is ignored.
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.
httpserver.SecurityHeaders(httpserver.WithHSTS(httpserver.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 ¶
ServerOption configures the *http.Server built by New. Only options that add a capability exist; every other field is a plain assignment on the returned server (see New).
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 New), so install the process logger before building the server; a later slog.SetDefault does not retroactively re-target an already-built http.Server. Any other *log.Logger is a plain assignment to srv.ErrorLog, and the default (net/http's standard logger) is unchanged when neither is set.
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 access library (github.com/cplieger/access), 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/go/httpserver"
)
func main() {
v := httpserver.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 := httpserver.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. The zero StatusRecorder is not usable; build one with NewStatusRecorder.
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 ¶
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.