httpserver

package module
v2.0.0-dev.6 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 45 Imported by: 3

README

httpserver

Go Reference Go version

httpserver hardens your Go net/http server with access logging, security headers, a client IP that cannot be spoofed and graceful shutdown, and serves a single-page app under a strict Content-Security-Policy.

Every piece is a plain http.Handler around http.ServeMux, so your app keeps its own routes and error codes. It ships no router, depends only on the standard library, golang.org/x/net/html, go/ssrf and go/textsafe, plus golang.org/x/sync and go/filesafe for imagecache, and is licensed under Apache-2.0.

Why use it

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

  • ResolveClient reads X-Forwarded-For only from a proxy you trust, so a client cannot fake its address. ForwarderCheck spots a container runtime's forwarder posing as a local client.
  • A Host allowlist stops DNS rebinding, and CrossOrigin refuses cross-site writes.
  • Every refusal is one JSON envelope with a code, a message, a remediation and the request id.
  • SPA serves only the files your bundle's manifest lists, with the policy on every answer and year-long caching for hashed assets. A stable entry, such as a service worker, keeps one URL at the root and revalidates on every load. httpservertest.CheckSPA checks every path in a test.
  • The access log caps the path and method it writes, and metric labels stay bounded.
  • imagecache serves an upstream's images from your own origin, each one's type checked against its bytes, kept in a bounded directory and answered with an ETag.
  • New leaves the write timeout off, so streams stay open. Run drains in-flight requests within a grace period, and the ops listener keeps /healthz answering through the drain.

Consider chi for route groups and sub-routers, or golang.org/x/time/rate for a limiter that waits instead of refusing.

Install

go get github.com/cplieger/go/httpserver/v2@latest

Usage

package main

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

	"github.com/cplieger/go/httpserver/v2"
)

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

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

	// Only header reads and idle connections time out, so streams stay open.
	// Every other http.Server field is a plain assignment.
	srv := httpserver.New(handler, httpserver.WithSlogErrorLog(slog.LevelError))
	streams, endStreams := context.WithCancel(context.Background())
	srv.BaseContext = func(net.Listener) context.Context { return streams }

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

	// Bind first, so a port still in use after Listen's 5 s retry fails here.
	ln, err := httpserver.Listen(ctx, httpserver.ListenSetting{Name: "LISTEN_ADDR", Addr: ":8080"})
	if err != nil {
		panic(err)
	}

	if err := httpserver.Run(ctx, srv, ln,
		// End long-lived streams so they do not hold the drain open.
		httpserver.WithPreDrain(func(context.Context) { endStreams() }),
		httpserver.WithTeardown(func(context.Context) {
			// close what the handlers used, after the drain
		}),
	); err != nil {
		panic(err)
	}
}

A service that browsers reach should also refuse unknown Host names. Build a HostPolicy with ParseHostList and put its Middleware() in the chain ahead of CrossOrigin, which guards the routes that change state. Each refusal logs one Warn line naming the reason and the host. An API that only machines call can skip it. The examples on pkg.go.dev run under go test, which keeps them true.

API

  • Middleware: Chain, Recoverer, SecurityHeaders with HSTS, Gzip, Logging, RouteTimeout, RouteDeadline, RateLimiter with its FailedAuthRateLimit preset, NewKeyedRateLimiter (KeyedRate, KeyedRateLimiter), NoStore.
  • Logging and metrics: Logging's options with WithProbeLogLevel and WithRecordRouteMetric (RequestMetric), AddLogAttrs for a handler's own access-line attributes, the request-id helpers (HeaderRequestID, NewRequestID, ValidRequestID, RequestIDFromContext, WithRequestID), StatusRecorder and NewStatusRecorder.
  • Trust checks: ClientIP, ResolveClient (ClientResolution), ParseCIDRs, ParseHostList and HostPolicy (with WithLoopbackExempt, WithIPLiteralHosts, WithHostResponder, WithHostAllowlistLogger and LogRefusal), CanonicalHost, CrossOrigin, LoopbackOnly, LoopbackRequest, ProxiedRequest, ClassifyBind and ClassifyBindHost, NewForwarderCheck (ForwarderCheck), NewStaticTokenVerifier, NewTokenSet (TokenSet, TokenSetError with its Err reasons, MaxTokenBytes), NewFailureLimiter (FailureLimiter, FailureLimits), CheckFieldValue (FieldValueError with its Err reasons), SetChallenge (Challenge, AuthParam).
  • Requests and responses: WriteJSON, WriteJSONStatus, OK, JSONHeaders, WriteError with ErrorResponse, ErrorCode and ErrorResponder, NewErrorResponse and WriteErrorBody (ErrorBody) for an envelope with its own remediation or fields, CodeSpecs (CodeSpec), DecodeBody, DecodeJSONInto with ErrTrailingData and MaxJSONBody, LimitBody, RequireMethod, MethodNotAllowed, SetAllow, CanonicalRequestPath.
  • Static files: StaticHandler with WithStaticCacheControl and WithStaticETags, ContentTypes, InlineScriptHashes, InlineStyleHashes.
  • Single-page apps: SPA (SPAConfig), Page, CheckPages, NewPageMatcher (PageMatcher, PageMatch), NotFound, the manifest (BundlePath, ReadBundle, Bundle, BundleEntry, BundleKind), SPAPolicy, CheckShell, and OutagePage (OutageConfig, OutageFile, OutageClass, OutageCommand).
  • Upstream images in imagecache: New (Options, Key, Image, Fetch), Cache.Serve, Forget, ForgetSpace, Shutdown, CodeSpecs.
  • Test helpers in httpservertest: CheckSPA, CheckNoUI, CheckCodeSpecs.
  • Server: New with WithSlogErrorLog, Run with WithPreDrain, WithTeardown, WithServeExit and WithShutdownGrace, ErrShutdownGraceExpired, AwaitDone, CausedByCancellation, and the ops listener for /healthz and /metrics: ListenAddr, ListenOps (OpsConfig, Ops), RunWithOps (Served), and Listen and CheckListenAddrs over ListenSetting.

The full reference is on pkg.go.dev.

Middleware order and safety rules

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

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

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

RouteTimeout buffers the whole response, so never wrap a streaming or hijacking handler with it. If the handler is still running at its deadline, it answers 503 without stopping it, so never wrap a handler that changes state with it either. Use RouteDeadline for that one. Middleware has each option and default.

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

Graceful shutdown

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

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

Moving from v1

  • Change every import of github.com/cplieger/go/httpserver to github.com/cplieger/go/httpserver/v2.
  • Read an error body's message key, which replaces error. code, remediation and request_id are always present.
  • Drop WithHostAllowlistError. The refusal is always 403 host_not_allowed, and WithHostResponder writes it through your own ErrorResponder.
  • Give every WriteError call and every ErrorResponder a non-empty code. The empty code is now malformed and answers invalid_error_code.
  • Replace ListenMetrics, MetricsHandlers and MetricsServer with ListenOps and RunWithOps, and pass every listener's address to CheckListenAddrs at start.
  • A client matching Recoverer's 500 message reads internal error.
  • ClientResolution.IgnoredPublic judges an ignored forwarded address as go/ssrf's IsPublicAddr does, so a shared (RFC 6598), documentation or other non-routable address no longer sets it.
  • A StaticHandler file with an extension outside the content-type table, such as .jpg or .woff, now answers application/octet-stream. Convert it to a listed format, or serve it with your own handler.
  • Code written against v2.0.0-dev.1 or v2.0.0-dev.2 calls ListenAddr where it called OpsAddr, with the same arguments.
  • A shell written against v2.0.0-dev.1 or v2.0.0-dev.2 that carries an on… event-handler attribute, such as onclick, is now refused by SPA and CheckShell. The policy already blocked the handler in the browser, so attach it from the bundle's script with addEventListener.
  • A shell that ends inside a <script> is now refused too, because the browser never ran that script: close it with </script>.
  • A shell nested deeper than 512 elements, or holding a <template> inside an <svg> or <math> integration point such as <foreignObject>, is now refused, because the check cannot read all of it: flatten the nesting, or move the <template> out of the <svg> or <math>. A <template> in svg markup itself is read as usual. A shell that spells <template more than 16 times after the first <svg or <math in its bytes, comments and attribute values included, is refused too: move the templates before it or into the bundle (the SPA policy).
  • Code written against v2.0.0-dev.1 wraps each OutageConfig.Commands string as httpserver.OutageCommand{Run: s}, since the field is now []OutageCommand. A line that explained a command moves into its Note, and a line about the outage as a whole into Notice.
  • httpclient makes the requests your service sends out survive flaky servers. httpserver handles the requests coming in.
  • health is the container liveness probe for a Docker HEALTHCHECK, and its CheckHandler answers a load balancer's readiness check.
  • access handles user logins and sessions. NewStaticTokenVerifier checks one configured machine credential, and TokenSet several.

Documentation

Credits

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

Contributing

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

Disclaimer

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

This project was built with AI assistance. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

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, KeyedRateLimiter, NoStore, LoopbackOnly), a spoof-aware ClientIP and ResolveClient, a Host allowlist against DNS rebinding (HostPolicy, CanonicalHost), a cross-origin write guard (CrossOrigin), one JSON error envelope (WriteError, ErrorResponse, CodeSpecs), request preludes (LimitBody, RequireMethod, DecodeBody), an embedded StaticHandler, single-page app serving from a bundle manifest (SPA, PageMatcher, OutagePage), a constant-time NewStaticTokenVerifier, ClassifyBind, a graceful server (New, Run, Listen) and the ops listener (ListenOps, RunWithOps, CheckListenAddrs). Package httpservertest checks an app's use of them.

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. The package depends on nothing beyond the standard library, golang.org/x/net/html, go/ssrf and go/textsafe.

Index

Examples

Constants

View Source
const (
	DefaultRouteFile     = "/proc/net/route"
	DefaultIPv6RouteFile = "/proc/net/ipv6_route"
)

The Linux route files ForwarderCheck reads by default.

View Source
const BundlePath = "bundle.json"

BundlePath is the manifest's path at the root of a bundle tree.

View Source
const DefaultShell = "index.html"

DefaultShell is the shell a Page with no Shell answers, and the shell SPA answers with 404 for a path that is no page.

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

View Source
const MaxJSONBody int64 = 1 << 20

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

View Source
const MaxTokenBytes = 512

MaxTokenBytes bounds a token TokenSet holds or matches. A presented value longer than this never matches and is refused before it is hashed.

Variables

View Source
var (
	ErrFieldControl     = errors.New("field value holds an ASCII control byte or DEL")
	ErrFieldEdgeSpace   = errors.New("field value starts or ends with a space or tab")
	ErrFieldInvalidUTF8 = errors.New("field value is not valid UTF-8")
	ErrFieldInvisible   = errors.New("field value holds an invisible character")
)

The reasons CheckFieldValue refuses a value, matched with errors.Is.

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

View Source
var (
	ErrNoTokens      = errors.New("no tokens configured")
	ErrTokenEmpty    = errors.New("token is empty")
	ErrTokenTooLong  = errors.New("token is longer than MaxTokenBytes")
	ErrTokenRepeated = errors.New("token repeats an earlier token")
)

The reasons a TokenSetError carries, matched with errors.Is.

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

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

func AddLogAttrs(ctx context.Context, attrs ...slog.Attr)

AddLogAttrs adds attrs to the access line Logging writes for the request ctx belongs to, after the line's own attributes, for what only a handler knows, such as the credential a request authenticated with. It is safe from any goroutine and does nothing without Logging, for a skipped request, or once the line is written. It drops an attribute with an empty key or one of the line's own keys, and any past the eighth. Each value is resolved when added: a string, or another value written as text, is cut at 256 bytes like an over-long path, and a group keeps its first eight members.

func AwaitDone

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

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

It deliberately creates NO timeout of its own and logs nothing. Run hands 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

func CanonicalHost(hostport string) string

CanonicalHost parses a Host header value or an allowlist entry into the key exact matching compares: lowercase, with no port, brackets or trailing dot, and an IP literal in net.IP's spelling. It is idempotent, and returns "" for anything that is not a well-formed RFC 3986 authority, never repairing one, since a repair maps distinct wire values onto an allowed key. The fold is ASCII-only: strings.ToLower maps U+212A and U+0130 to "k" and "i". ssrf's numeric-IPv4 check refuses dotted hex, which this accepts as a name; the two answer different questions and stay separate.

func CanonicalRequestPath

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

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

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

Why a library surface exists for this

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

Which value to pass, and what that means

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

What canonical does NOT claim

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

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

Edge inputs

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

What stays the caller's

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

func CausedByCancellation

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

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

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

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

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

func Chain

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

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

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

handler := 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 CheckFieldValue

func CheckFieldValue(v string) error

CheckFieldValue reports whether v can be sent verbatim as an HTTP field value (RFC 9110 section 5.5) and read back unchanged: no ASCII control byte but HTAB, no DEL, no space or tab at an edge (a recipient strips it), valid UTF-8, and no invisible rune (a C1 control, a format character such as a bidi control or zero-width space, a line or paragraph separator). A refusal is a *FieldValueError naming the first refused byte. The empty string passes; length and blank-value policy stay the caller's.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/cplieger/go/httpserver/v2"
)

func main() {
	err := httpserver.CheckFieldValue("a-token-pasted-with-a-newline\n")
	fmt.Println(errors.Is(err, httpserver.ErrFieldControl), err)
}
Output:
true httpserver: field value holds an ASCII control byte or DEL at byte 29

func CheckListenAddrs

func CheckListenAddrs(settings ...ListenSetting) error

CheckListenAddrs refuses, naming both settings and the port, every pair of settings that would bind one socket: the same port as net.Listen resolves it (09737 is 9737, http is 80) with the same host, or with either host unspecified (empty, 0.0.0.0 or [::], each overlapping every address on its port, since on Linux Go's "tcp" [::] listener takes IPv4 too) or a name, which may resolve to the other's address. A blank value, a port of 0 and a value with no resolvable port pass, the last left to net.Listen. Each value is read through ListenAddr. Pass every listener the app opens, once.

func CheckPages

func CheckPages(pages []Page) error

CheckPages refuses a page table SPA cannot serve: more than 256 pages or 8 shells; a name that is empty, repeated or not an ASCII identifier; a pattern that is not a valid ServeMux pattern, names a method or a host, or conflicts with another as ServeMux judges conflicts (two patterns that each match a path the other does, neither more specific, a repeated pattern included); and a shell that is not an .html file name at the root.

func CheckShell

func CheckShell(body []byte) error

CheckShell refuses a shell SPA's policy would block, read as html.Parse builds its document: an inline script or style element, a style or on* event-handler attribute, or a script left open at end of input. It refuses a shell html.Parse cannot read whole: past 512 nested elements, or a <template> in an svg or math integration point such as <foreignObject> (one in svg markup itself is read). Its own limit refuses over 16 <template spellings after the first <svg or <math in the bytes, comments and attributes included. The error names the element, and the attribute where one is the cause.

func ClientIP

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

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

func CodeSpecs

func CodeSpecs() map[ErrorCode]CodeSpec

CodeSpecs returns every code a writer in this package answers, with its status and default remediation. The map is the caller's own copy.

func ContentTypes

func ContentTypes() map[string]string

ContentTypes returns a copy of the fixed content-type table StaticHandler and SPA answer from, keyed by extension with its dot (".js"). A file whose extension is outside it answers application/octet-stream from StaticHandler; a bundler refuses to write one.

func CrossOrigin

func CrossOrigin(next http.Handler, errs ErrorResponder) http.Handler

CrossOrigin serves next behind http.CrossOriginProtection, answering a refused request with cross_origin_refused (403) as the envelope through errs (nil: WriteError). It refuses an unsafe method whose Sec-Fetch-Site is not same-origin or none, or, with no Sec-Fetch-Site, whose Origin is not the request's host; GET, HEAD, OPTIONS and a request with neither header pass.

func DecodeBody

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

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

func DecodeJSONInto

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

DecodeJSONInto caps the body at maxBytes (LimitBody) and decodes exactly one JSON value into v, writing nothing to w. Its error is a *http.MaxBytesError past the cap (the caller picks 413 or 400), ErrTrailingData when a second value follows, or the decoder's own error for a malformed or empty body. DecodeBody is this at MaxJSONBody plus a 400 bad_request.

func InlineScriptHashes

func InlineScriptHashes(page []byte) []string

InlineScriptHashes returns a CSP source token 'sha256-<base64>' for each inline script element, HTML or SVG, in page's document as html.Parse builds it, hashing its text as a browser does. A script a browser never checks against the policy is skipped: one with a source, a data block, and one left open at end of input. A page CheckShell refuses as one html.Parse cannot read whole yields nil, as a script-less page does, which a caller whose page holds an inline script treats as a broken build rather than loosening its policy. It reads pages the app controls and is not a sanitizer.

func InlineStyleHashes

func InlineStyleHashes(page []byte) []string

InlineStyleHashes returns a CSP source token for each style element, HTML or SVG, in page, as InlineScriptHashes does for scripts. A style left open at end of input is hashed, since a browser applies it. It covers style elements only: a style attribute needs style-src-attr, which no element hash satisfies. It yields nil for the pages InlineScriptHashes does.

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 Listen

func Listen(ctx context.Context, s ListenSetting) (net.Listener, error)

Listen binds s.Addr, read through ListenAddr, over TCP. A blank Addr is an error. A port in use (EADDRINUSE) is retried every 250 ms for up to 5 s; another error, or ctx ending, fails at once. The error names s.Name and the address, control characters cleaned, and wraps the cause.

func ListenAddr

func ListenAddr(value, def string) string

ListenAddr is a listener's address from its setting's raw value, such as LISTEN_ADDR's or OPS_LISTEN_ADDR's: edge spaces and invisible runes cut, and def, the app's documented address, for a blank value. A def of "" returns "" for a blank value.

func LoopbackRequest

func LoopbackRequest(r *http.Request) bool

LoopbackRequest reports whether r came from this host's own network stack: its socket peer is loopback and its Host names the local host, or its peer is the connection's own local address and its Host is that address. Both legs must hold, and each fails closed on a malformed value. It reads r.RemoteAddr, r.Host and the local address http.Server records, never a forwarded header. It decides admission only, for a loopback-only route. Unlike HostPolicy, whose allowlist admits a remote caller sending an allowed Host such as localhost, nothing outside this host can satisfy it.

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/v2"
)

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.
	r := httptest.NewRequest(http.MethodDelete, "/things", nil)
	r = r.WithContext(httpserver.WithRequestID(r.Context(), "req-2"))
	httpserver.MethodNotAllowed(rr, r, http.MethodGet, http.MethodPost)
	fmt.Println(rr.Code)
	fmt.Println(rr.Header().Get("Allow"))
	fmt.Print(rr.Body.String())
}
Output:
405
GET, POST
{"code":"method_not_allowed","message":"method not allowed","remediation":"Resend with a method the Allow header lists.","request_id":"req-2"}

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 NotFound

func NotFound(errs ErrorResponder) http.Handler

NotFound answers every request with not_found (404) through errs, nil being WriteError: the root of a build with no web UI.

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/v2"
)

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

func OutagePage

func OutagePage(c OutageConfig) (http.Handler, error)

OutagePage serves the static page an app shows while a file it needs cannot open: every GET or HEAD outside APIPrefix answers 503, no-store, under SPAPolicy's default policy, with the title, the closing line and each file's class sentence as given, and each file's Name, the Notice and each command's Run and Note cleaned through textsafe. A listed asset or stable entry answers as SPA serves it; a path at or under APIPrefix answers not_found and another method method_not_allowed, through Errors, no-store. The error names the refused field (a blank Title or App too), class or bundle.

Example
package main

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

	"github.com/cplieger/go/httpserver/v2"
)

func main() {
	page, err := httpserver.OutagePage(httpserver.OutageConfig{
		Title:     "myapp cannot start",
		App:       "myapp",
		APIPrefix: "/api",
		Files:     []httpserver.OutageFile{{Name: "ACCOUNTS_PATH, /config/accounts.db", Class: httpserver.OutageNewer}},
		Notice:    "Sign-in is off until the accounts file opens.",
		Commands: []httpserver.OutageCommand{{
			Run:  "docker exec myapp myapp accounts restore <archive>",
			Note: "Restores the accounts file from an export archive.",
		}},
	})
	if err != nil {
		panic(err)
	}
	rec := httptest.NewRecorder()
	page.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/library", nil))
	fmt.Println(rec.Code, rec.Header().Get("Cache-Control"))

	_, err = httpserver.OutagePage(httpserver.OutageConfig{
		Title: "myapp cannot start", App: "myapp", APIPrefix: "/api",
		Files: []httpserver.OutageFile{{Name: "DATA_PATH", Class: "corrupt"}},
	})
	fmt.Println(err)
}
Output:
503 no-store
httpserver: outage file "DATA_PATH" has class "corrupt"; want damaged, format, newer, unreadable, key or unwritable

func ParseCIDRs

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

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

func ProxiedRequest

func ProxiedRequest(h http.Header) bool

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

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

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

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

func RequireMethod

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

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

if !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

func RouteDeadline(h http.Handler, d time.Duration) http.Handler

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

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

RouteTimeout answers 503 with a JSON ErrorResponse (code "timeout", msg or "request timed out") 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

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

Run serves srv on ln until ctx is cancelled, then shuts down within one grace period (WithShutdownGrace): the WithPreDrain hook, srv.Shutdown, then 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 RunWithOps

func RunWithOps(ctx context.Context, ops *Ops, served ...Served) error

RunWithOps serves every Served with Run, and ops beside them, until ctx ends or one fails, which stops the rest; every error is joined. The ops listener stops only after every product Run has returned, so /healthz answers through their drain, then within its own 1 s grace, a request cut there logged at WARN, not returned. Either side may be empty; with neither it returns nil. It owns every listener given, closing them when ListenOps's context ended first. It panics on a Served with a nil Server or Listener.

func SPA

func SPA(c SPAConfig) (http.Handler, error)

SPA serves a single-page app's bundle (BundlePath) for GET and HEAD. A listed asset answers through StaticHandler (immutable; a BundleClassic or stable entry no-cache), a notice text/plain, /favicon.ico 204, any other path under assets/ or licenses/ a refusal, whatever the pages match; then a page path answers its shell, any other the default shell with 404, no-cache. A path at or under APIPrefix, a dot segment no page matches, another method and, unbuilt, a page (ui_unbuilt) answer a refusal through Errors, no-store. Every answer carries SPAPolicy's policy and every no-cache ETag binds it.

Example
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing/fstest"

	"github.com/cplieger/go/httpserver/v2"
)

// exampleBundle is a built tree as a bundler writes it: a shell, one module
// entry and its manifest.
func exampleBundle() fstest.MapFS {
	fsys := fstest.MapFS{
		"index.html":         {Data: []byte(`<!doctype html><script type="module" src="/assets/app-3f2a.js"></script>`)},
		"assets/app-3f2a.js": {Data: []byte(`console.log("app")`)},
	}
	b := httpserver.Bundle{
		Files:   map[string]string{},
		Entries: []httpserver.BundleEntry{{Name: "app", Kind: httpserver.BundleModule, Path: "assets/app-3f2a.js"}},
	}
	for name, f := range fsys {
		sum := sha256.Sum256(f.Data)
		b.Files[name] = hex.EncodeToString(sum[:])
	}
	manifest, _ := json.Marshal(b)
	fsys[httpserver.BundlePath] = &fstest.MapFile{Data: manifest}
	return fsys
}

func main() {
	ui, err := httpserver.SPA(httpserver.SPAConfig{
		Assets:    exampleBundle(),
		Pages:     []httpserver.Page{{Name: "home", Pattern: "/{$}"}, {Name: "item", Pattern: "/items/{id}"}},
		APIPrefix: "/api",
	})
	if err != nil {
		panic(err)
	}
	for _, path := range []string{"/items/7", "/assets/app-3f2a.js", "/assets/gone.js", "/nowhere"} {
		rec := httptest.NewRecorder()
		ui.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
		fmt.Printf("%s %d %s %q\n", path, rec.Code, rec.Header().Get("Content-Type"), rec.Header().Get("Cache-Control"))
	}
}
Output:
/items/7 200 text/html; charset=utf-8 "no-cache"
/assets/app-3f2a.js 200 text/javascript; charset=utf-8 "public, max-age=31536000, immutable"
/assets/gone.js 404 application/json "no-store"
/nowhere 404 text/html; charset=utf-8 "no-cache"

func SPAPolicy

func SPAPolicy(add map[string][]string) (string, error)

SPAPolicy returns the Content-Security-Policy SPA writes for add, the SPAConfig.CSPAdd value, and the error SPA refuses add with: a directive other than img-src, media-src or font-src, a source other than blob: or data:, an empty list, and a source the directive already holds.

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 SetChallenge

func SetChallenge(h http.Header, c Challenge, more ...Challenge)

SetChallenge replaces h's WWW-Authenticate field with one line per challenge, in order, so a 401 names how to authenticate (RFC 9110 section 11.6.1 requires at least one challenge on a 401). It sets the header only.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/cplieger/go/httpserver/v2"
)

func main() {
	h := http.Header{}
	httpserver.SetChallenge(h, httpserver.Challenge{
		Scheme: "Bearer",
		Params: []httpserver.AuthParam{{Name: "realm", Value: "myapp"}},
	})
	fmt.Println(h.Get("WWW-Authenticate"))
}
Output:
Bearer realm="myapp"

func StaticHandler

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

StaticHandler serves fsys, typically an embed.FS, whose zero ModTime leaves a bare http.FileServer nothing to revalidate on. It reads the tree once and gives each file a sha256 ETag (or the WithStaticETags tag) and, when smaller, a gzip body. Every file answers its type from ContentTypes. A tagged file 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 when walking fsys fails or WithStaticETags is refused.

func ValidRequestID

func ValidRequestID(s string) bool

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

Example
package main

import (
	"fmt"

	"github.com/cplieger/go/httpserver/v2"
)

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

func WithRequestID

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

WithRequestID returns a copy of ctx carrying the request id.

func WriteError

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

WriteError writes the ErrorResponse for code and msg with the given status. It sets Content-Type, and X-Request-ID when the response has none, and keeps every other header the caller set. r may be nil. It is WriteErrorBody(w, status, NewErrorResponse(r, code, msg)).

WriteError ships the mechanism only; each application keeps its own code taxonomy on top of it.

Example
package main

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

	"github.com/cplieger/go/httpserver/v2"
)

func main() {
	rr := httptest.NewRecorder()
	// Logging puts the request id in the context; without one WriteError
	// mints a fresh id.
	r := httptest.NewRequest(http.MethodPost, "/things", nil)
	r = r.WithContext(httpserver.WithRequestID(r.Context(), "req-1"))
	httpserver.WriteError(rr, r, http.StatusBadRequest, "bad_request", "invalid payload")
	fmt.Print(rr.Body.String())
}
Output:
{"code":"bad_request","message":"invalid payload","remediation":"Fix the request as the message describes, then resend it.","request_id":"req-1"}

func WriteErrorBody

func WriteErrorBody(w http.ResponseWriter, status int, body ErrorBody)

WriteErrorBody writes body as JSON with status. It sets Content-Type, and X-Request-ID to the body's RequestID when the response has none, so the header and the body carry one id; every other header the caller set stays. The body's ErrorResponse is the caller's to build with NewErrorResponse, changing Message or Remediation at most: one built otherwise is written as it is, its code unchecked and no request id filled.

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 AuthParam

type AuthParam struct {
	Name  string
	Value string
}

AuthParam is one auth-param of a challenge, rendered as name="value".

type BindClass

type BindClass int

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

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

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

func ClassifyBind

func ClassifyBind(addr string) BindClass

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

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

// Fail-silent (web-terminal-kiro): an unparseable addr will fail at
// Listen anyway; only a definite exposure warrants the warning.
if 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

func ClassifyBindHost(host string) BindClass

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

func (BindClass) String

func (c BindClass) String() string

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

type Bundle

type Bundle struct {
	Files   map[string]string `json:"files"`
	Entries []BundleEntry     `json:"entries"`
}

Bundle is the manifest a bundler writes at BundlePath: every file it wrote, by its path in the tree, with its SHA-256 in lowercase hex, and every entry it built. SPA serves only the files it lists.

func ReadBundle

func ReadBundle(fsys fs.FS) (Bundle, bool, error)

ReadBundle reads fsys's manifest; found is false with a nil error when fsys is nil or holds no BundlePath (unbuilt). A manifest that does not read, decode or check is an error. Each listed path is a regular file in fsys with no dot segment: a root .html shell, a stable entry's root .js file, or a file under assets/ or licenses/ other than index.html. Each entry's logical path is unique and its Path is a listed file, under assets/ unless Stable.

type BundleEntry

type BundleEntry struct {
	Name   string     `json:"name"`
	Kind   BundleKind `json:"kind"`
	Path   string     `json:"path"`
	Stable bool       `json:"stable,omitempty"`
}

BundleEntry is one built entry: its logical name ("app" for "/app.js" or "/app.css" in a shell), its kind and its hashed path in the tree. A Stable entry keeps one URL across builds, such as a service worker's: its Path is an unhashed .js file at the tree root, which SPA serves no-cache.

type BundleKind

type BundleKind string

BundleKind is how a bundle entry was built.

const (
	BundleModule  BundleKind = "module"  // ESM with shared chunks
	BundleClassic BundleKind = "classic" // a self-contained script: the prepaint, a worker host
	BundleStyle   BundleKind = "style"   // CSS
)

The kinds a bundler writes.

type Challenge

type Challenge struct {
	Scheme string
	Params []AuthParam
}

Challenge is one RFC 9110 section 11.6.1 challenge for a WWW-Authenticate field: an auth-scheme and its auth-params, such as Bearer with realm="knell". It renders the header only; the response's status and body stay the caller's.

func (Challenge) String

func (c Challenge) String() string

String renders the challenge: the scheme, then each param as name="value" with the value a quoted-string, separated by ", ". It panics when the scheme or a param name is not an RFC 9110 token, or a value cannot be a quoted-string (CheckFieldValue refuses it for a control byte, invalid UTF-8 or an invisible rune), since those come from the program, not a request. A value taken from outside the program is checked with CheckFieldValue first.

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, as ssrf.IsPublicAddr judges one.
	IgnoredPublic bool
	// ForwardedHTTPS reports that a trusted peer said the client reached it
	// over TLS: exactly one X-Forwarded-Proto field holding the one token
	// https, any case. A list, a repeated field or an untrusted peer reads as
	// plain, so a proxy must overwrite the client's field, not append to it.
	ForwardedHTTPS 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 CodeSpec

type CodeSpec struct {
	Remediation string
	Status      int
	NoEffect    bool
}

CodeSpec is what an error code means to a client: the status it is answered with, one line telling a person or a script what to do next, and whether the refused request changed nothing, so a resend is safe.

type ErrorBody

type ErrorBody interface {
	// contains filtered or unexported methods
}

ErrorBody is an ErrorResponse, or a struct that embeds one by value, so an application can answer its own fields beside the standard envelope.

type ErrorCode

type ErrorCode string

ErrorCode is the machine token in the envelope's "code" field, the value a client branches on and a log query keys on. It is typed apart from the message so a call site cannot transpose the pair.

The grammar is one or more lowercase ASCII letters, digits and underscores ("host_not_allowed"). A code outside it, the empty code included, is never repaired and never panics: the envelope carries InvalidErrorCode instead and the offender is logged once per process.

const InvalidErrorCode ErrorCode = "invalid_error_code"

InvalidErrorCode is written in place of a malformed code. It is its own code, not internal_error, so a broken code never relabels a 400 as a server fault.

type ErrorResponder

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

ErrorResponder renders an error response body; WriteError is its canonical instance and the library-wide default. Middleware that emits an error body (Recoverer via WithRecoverResponder, RateLimiter via WithRateLimitResponder) takes one, so an XML or plain-text service keeps its own content type. A responder writes the status and any headers, and runs only before the response is committed. It receives the ErrorCode unvalidated: one that emits the code in a machine-readable slot builds its body with NewErrorResponse and writes it with WriteErrorBody, or checks the code the same way.

type ErrorResponse

type ErrorResponse struct {
	Code        ErrorCode `json:"code"`
	Message     string    `json:"message"`
	Remediation string    `json:"remediation"`
	RequestID   string    `json:"request_id"`
}

ErrorResponse is the JSON error envelope. Every key is always present. In one NewErrorResponse builds, and so in every one WriteError writes, RequestID is the request's id, or a fresh one when its context has none, and Remediation is the code's CodeSpec default, or empty for a code outside CodeSpecs. A struct that embeds it by value as its first field marshals flat, its four keys first and the embedder's own after.

func NewErrorResponse

func NewErrorResponse(r *http.Request, code ErrorCode, msg string) ErrorResponse

NewErrorResponse returns the envelope WriteError writes for code and msg: a malformed code replaced by InvalidErrorCode, the code's CodeSpecs remediation (empty outside CodeSpecs), and the request id from r's context, else a fresh one. r may be nil. A caller may replace Remediation, or embed the result in a struct of its own, before WriteErrorBody writes it.

type FailureLimiter

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

FailureLimiter throttles clients that keep failing to authenticate, by client key and across every key, without ever being moved by a request it throttles. It is for a handler that must check a credential before it can tell the client anything: the handler asks Decide once per request and answers a throttled request the same way whatever it presented.

A key is a client address, an IPv4 address whole and an IPv6 address masked to FailureLimits.IPv6Prefix bits; an invalid address is one shared key. A key the application marks good, under a group it names, is exempt from the global window while the mark lasts and the key's own window holds no failure, so a spray across many addresses cannot throttle a client that has recently succeeded.

All state is in memory and resets at a restart. It logs nothing and returns no error after construction, so a group name never leaves it. It is safe for concurrent use; every method runs under one lock.

func NewFailureLimiter

func NewFailureLimiter(l FailureLimits) (*FailureLimiter, error)

NewFailureLimiter checks l and returns a limiter, or an error naming the first field out of range.

func (*FailureLimiter) Decide

func (f *FailureLimiter) Decide(client netip.Addr, failure bool) (throttled bool, wait time.Duration)

Decide is the limiter's one question per request. It reports whether client is throttled, and for how long, from the state before this request: when its key's window is full, or when the global window is full and the key is not exempt. wait is the longer of the waits that apply. A throttled answer changes nothing, so a throttled request can neither charge a window nor move a key in or out of the held set. When the answer is not throttled and failure is true, the failure is charged to the key's window and the global window. Asking once per request, before anything is written, is what keeps concurrent requests from passing a full window together.

func (*FailureLimiter) MarkGood

func (f *FailureLimiter) MarkGood(group string, client netip.Addr)

MarkGood records that client succeeded for group, a name the application takes from its configuration, never from the request. A key the group already holds has its mark refreshed; a new key joins the group, replacing the group's own oldest mark when it already holds TrustPerGroup keys and never touching another group's. Call it only after a request the limiter did not throttle succeeded.

type FailureLimits

type FailureLimits struct {
	// Now is the limiter's clock; nil means time.Now. A test passes a fake
	// clock here to step through the windows.
	Now func() time.Time
	// PerKey is how many failures one client key may make per PerKeyWindow
	// before Decide throttles it. Both must be positive.
	PerKey       int
	PerKeyWindow time.Duration
	// Global is how many failures every key together may make per
	// GlobalWindow before Decide throttles keys that are not exempt. Zero
	// turns the global window off, and GlobalWindow must then be zero too.
	Global       int
	GlobalWindow time.Duration
	// MaxKeys is how many keys' failures the limiter holds; charging a new
	// key past it forgets the least recently charged one. It must be
	// positive.
	MaxKeys int
	// TrustPerGroup is how many keys one group trusts at once, and
	// TrustWindow how long a mark lasts. Both must be positive.
	TrustPerGroup int
	TrustWindow   time.Duration
	// IPv6Prefix is how many leading bits of an IPv6 address make its key,
	// from 1 to 128; zero means 64 (RFC 6177's end-site /64).
	IPv6Prefix int
}

FailureLimits configures a FailureLimiter.

type FieldValueError

type FieldValueError struct {
	// Err is one of ErrFieldControl, ErrFieldEdgeSpace, ErrFieldInvalidUTF8
	// and ErrFieldInvisible.
	Err error
	// Offset is the byte offset of the refused byte or rune.
	Offset int
}

FieldValueError is CheckFieldValue's refusal. It names the reason and the byte offset of the first refused byte, never the value, so a caller can word a configuration error without quoting a secret.

func (*FieldValueError) Error

func (e *FieldValueError) Error() string

func (*FieldValueError) Unwrap

func (e *FieldValueError) Unwrap() error

type ForwarderCheck

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

ForwarderCheck reports whether a socket peer is a forwarder in front of this host, such as Docker's bridge gateway, rootless Podman's slirp4netns address or the Swarm ingress, each relaying a remote client under its own address. It re-reads the route tables and interfaces on every call, and a failed read, as on a host without Linux's route files, answers true so the caller fails closed. It is safe for concurrent use.

func NewForwarderCheck

func NewForwarderCheck(opts ...ForwarderOption) *ForwarderCheck

NewForwarderCheck returns a check over this host's network, or over the sources the options name.

func (*ForwarderCheck) IsForwarder

func (c *ForwarderCheck) IsForwarder(peer netip.Addr) bool

IsForwarder reports that peer is a gateway of any route, an address of a non-loopback interface, or inside a connected subnet of an interface that carries no default route of peer's family. Its zone is dropped and an IPv4-mapped address compares as IPv4. An invalid address, a nil check and a failed read of either source each answer true. A failed read logs one Warn line per source for the check's life.

type ForwarderOption

type ForwarderOption func(*ForwarderCheck)

ForwarderOption configures NewForwarderCheck.

func WithForwarderLogger

func WithForwarderLogger(logger *slog.Logger) ForwarderOption

WithForwarderLogger sends the failed-read warning to logger. Nil, the default, means slog.Default() as it is when the warning is logged.

func WithInterfaceAddrs

func WithInterfaceAddrs(read func() ([]InterfaceAddrs, error)) ForwarderOption

WithInterfaceAddrs replaces the read of the host's interfaces, which is net.Interfaces by default. A nil func keeps the default.

func WithRouteFiles

func WithRouteFiles(ipv4, ipv6 string) ForwarderOption

WithRouteFiles reads the IPv4 and IPv6 route tables from these paths, in the formats of Linux's /proc/net/route and /proc/net/ipv6_route. An empty path keeps its default. An absent IPv6 file reads as no IPv6 routes, as on a kernel without IPv6; an absent IPv4 file is a failed read.

type GzipOption

type GzipOption func(*gzipConfig)

GzipOption configures Gzip.

func WithGzipMinBytes

func WithGzipMinBytes(n int) GzipOption

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

func WithGzipSkip

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

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

func WithGzipTypes

func WithGzipTypes(types ...string) GzipOption

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

type HSTS

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

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

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

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

func (HSTS) Validate

func (h HSTS) Validate() error

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

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

type HostAllowlistOption

type HostAllowlistOption func(*hostPolicyConfig)

HostAllowlistOption configures a HostPolicy built by ParseHostList.

func 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 the refusal is logged. Pass a logger with a discarding handler to silence it.

func WithHostResponder

func WithHostResponder(fn ErrorResponder) HostAllowlistOption

WithHostResponder sets the ErrorResponder that writes Middleware's refusal, in place of WriteError: it receives 403, host_not_allowed and "host not allowed", so an application's catalog writes its own remediation. A nil fn keeps WriteError.

func WithIPLiteralHosts

func WithIPLiteralHosts(admit bool) HostAllowlistOption

WithIPLiteralHosts selects whether a Host that is an IP address passes beside the allowlist: IPv4 or IPv6, bracketed IPv6 optionally with a zone as netip.ParseAddr reads one, and a port wherever CanonicalHost takes one. A deployment reached by address keeps working with no entry per address. It is safe because DNS rebinding needs the attacker's name in Host, and an address literal names no one's domain; a name stays under the exact-match list. False, the default, is the same as leaving it out, and options are last-wins.

func WithLoopbackExempt

func WithLoopbackExempt(exempt bool) HostAllowlistOption

WithLoopbackExempt selects whether a request from this host's own network stack bypasses the allowlist: a socket peer and Host that are both loopback, or a peer at the connection's own local address with that address as Host (the probe of a service bound to one non-loopback address). It keeps a container healthcheck or in-container client working under an allowlist of browser hostnames; neither a rebinding request (the attacker's name in Host) nor a remote peer can pass. False, the default, is the same as leaving it out, and options are last-wins.

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 allowlist entries into a HostPolicy and returns the entries it could not use, as ParseCIDRs does. Each entry is trimmed and canonicalized by CanonicalHost; a blank one is skipped. The policy is inactive (every Host passes) only when no entry is non-blank; any non-blank entry makes it active, so a list of only malformed entries refuses every request instead of switching the check off. A caller that must fail loud refuses to start on a non-empty invalid slice.

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, when WithIPLiteralHosts was set and the Host is an IP address, or, when WithLoopbackExempt was set, when the request is local by LoopbackRequest's rule. 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

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), or slog.Default as it is at that moment when the policy has none or is nil. 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 403 host_not_allowed through its responder (WithHostResponder) before the next handler runs, and logs one Warn with the reason, host, remote 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 InterfaceAddrs

type InterfaceAddrs struct {
	Name     string
	Prefixes []netip.Prefix
	Loopback bool
}

InterfaceAddrs is one network interface as a ForwarderCheck reads it: its name, its address prefixes, and whether it is a loopback interface.

type KeyedRate

type KeyedRate struct {
	Burst    int           // tokens a key may spend at once and its initial fill; default 40, 1 to 10,000
	Interval time.Duration // the time to accrue one token; default 50 ms (20 a second), 1 ms to 1 hour
	MaxKeys  int           // buckets held at once; default 10,000, 16 to 1,000,000
}

KeyedRate configures a KeyedRateLimiter. A zero field takes its default.

type KeyedRateLimiter

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

KeyedRateLimiter gives each key its own token bucket. A bucket refilled to its burst is forgotten wherever it sits, and past MaxKeys the least recently used bucket is dropped, so memory is bounded by MaxKeys. It is safe for concurrent use.

func NewKeyedRateLimiter

func NewKeyedRateLimiter(c KeyedRate) (*KeyedRateLimiter, error)

NewKeyedRateLimiter builds a limiter from c, refusing a field outside its range and naming it.

func (*KeyedRateLimiter) Middleware

func (l *KeyedRateLimiter) Middleware(key func(*http.Request) (string, bool), errs ErrorResponder) Middleware

Middleware takes one token of the bucket key names for each request. A request whose key answers false passes untouched; a refused one answers rate_limited (429) through errs (nil: WriteError) with Retry-After in whole seconds rounded up, at least 1, and does not reach next. key must not be nil.

Example
package main

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

	"github.com/cplieger/go/httpserver/v2"
)

func main() {
	limiter, err := httpserver.NewKeyedRateLimiter(httpserver.KeyedRate{Burst: 1, Interval: time.Minute})
	if err != nil {
		panic(err)
	}
	byKey := func(r *http.Request) (string, bool) {
		key := r.Header.Get("X-Api-Key")
		return key, key != ""
	}
	h := limiter.Middleware(byKey, nil)(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))

	for _, key := range []string{"a", "a", "b"} {
		r := httptest.NewRequest(http.MethodGet, "/things", nil)
		r.Header.Set("X-Api-Key", key)
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, r)
		fmt.Printf("%s %d %q\n", key, rec.Code, rec.Header().Get("Retry-After"))
	}
}
Output:
a 200 ""
a 429 "60"
b 200 ""

func (*KeyedRateLimiter) Take

func (l *KeyedRateLimiter) Take(key string) (wait time.Duration, ok bool)

Take spends one token of key's bucket, or answers how long until one is back; a refused take spends nothing.

type ListenSetting

type ListenSetting struct{ Name, Addr string }

ListenSetting is one TCP listener's setting and value, such as {"LISTEN_ADDR", ":9737"}.

type LogOption

type LogOption func(*logConfig)

LogOption configures Logging.

func WithClientIP

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

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

func WithClientIPFunc

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

WithClientIPFunc is like WithClientIP but resolves the "client_ip" attribute with a caller-supplied function instead of a fixed trusted-proxy set. Use it when the trusted set is not known at construction — e.g. it is reloaded from config at runtime behind a hot-reloadable resolver — or when client-IP resolution is otherwise app-specific: fn is called once per logged request (never on a skipped path), and its result is logged verbatim as "client_ip". It composes with 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

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

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

func WithLogger(l *slog.Logger) LogOption

WithLogger sets the slog.Logger used for access-log lines. Nil, the default, means slog.Default() as it is when each line is logged.

func WithMaxLoggedPath

func WithMaxLoggedPath(n int) LogOption

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

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

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

func WithPathFunc

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

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

The returned value is "the path as recorded": it feeds the access line's "path" attribute 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

func WithProbeLogLevel(paths ...string) LogOption

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/v2"
)

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

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

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

func WithSkipPaths

func WithSkipPaths(paths ...string) LogOption

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

func WithSkipUpgrades

func WithSkipUpgrades(skip bool) LogOption

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

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

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

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

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

Two boundaries, because both KEEP their record:

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

It takes no status argument on purpose. 101 is the one status that means the exchange ended rather than completed, so a general skip-these-statuses option would add exactly one capability: silencing refusals. A 404 flood is a broken route and a 401 flood is an attack, and deleting their records is CWE-778 rather than noise control — which WithLogLevel (or the 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

func WithTemplatePathsUnder(prefixes ...string) LogOption

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

type 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. A code outside CodeSpecs carries an empty remediation.

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 Middleware

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

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

func FailedAuthRateLimit

func FailedAuthRateLimit(when func(*http.Request) bool, msg string, 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/v2"
)

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 middleware that admits a request only when LoopbackRequest passes and ProxiedRequest finds no forwarding or browser header, and answers every other request 403 through WriteError with the code "loopback_only". The header check refuses a same-host reverse proxy that sends one, since such a proxy rewrites Host to its upstream address and so passes LoopbackRequest. It is not authentication: a same-host proxy that sends none passes. WithLoopbackError sets the code and message, WithLoopbackResponder the renderer.

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 and per-key limits are KeyedRateLimiter.

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 recovers a downstream panic, logs it at Error with its stack and request id, fires any WithPanicHook, and answers 500 internal_error through its ErrorResponder (WriteError unless WithRecoverResponder). It re-panics http.ErrAbortHandler, as net/http requires, and writes nothing when the handler had already committed the response. Put it inside Logging (Chain(mux, Logging(), Recoverer())) so the access line records the 500; outside it, Logging's deferred line records 200.

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 Ops

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

Ops is a bound ops listener. Serve it with RunWithOps.

func ListenOps

func ListenOps(ctx context.Context, c OpsConfig) (*Ops, error)

ListenOps binds the ops listener with Listen, Setting naming Addr, before it returns: GET and HEAD on /healthz and /metrics only, under WithProbeLogLevel and Recoverer, with a 10 s read and 30 s write timeout, and refusals through Errors. With Hosts empty every Host is answered; otherwise a Host outside Hosts is refused unless LoopbackRequest holds. A nil handler is an error even with the listener off. The listener closes when ctx ends before RunWithOps takes it. docs/server.md has the rest.

func (*Ops) Addr

func (o *Ops) 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.

type OpsConfig

type OpsConfig struct {
	// Metrics answers GET /metrics; required.
	Metrics http.Handler
	// Healthz answers GET /healthz; required.
	Healthz http.Handler
	// Errors writes every refusal; nil is WriteError.
	Errors ErrorResponder
	// Logger takes the access lines, refusals and recovered panics; nil is
	// slog.Default() as it is when each line is logged.
	Logger *slog.Logger
	// Setting names the setting Addr came from ("OPS_LISTEN_ADDR") in errors.
	Setting string
	// HostsSetting names the setting Hosts came from ("ALLOWED_HOSTS") in the
	// error for an entry no Host can match; blank is "OpsConfig.Hosts".
	HostsSetting string
	// Addr is read through ListenAddr; blank opens nothing.
	Addr string
	// Hosts, when it has a non-blank entry, are the host names or IP literals
	// answered besides loopback's; empty answers every Host.
	Hosts []string
}

OpsConfig configures ListenOps.

type OutageClass

type OutageClass string

OutageClass is why a file cannot open, from a closed set: OutagePage refuses any value but the six constants.

const (
	OutageDamaged    OutageClass = "damaged"    // "The file is damaged."
	OutageFormat     OutageClass = "format"     // "The file was written by another version of <app>, or is not <app>'s file."
	OutageNewer      OutageClass = "newer"      // "The file was written by a newer version of <app>."
	OutageUnreadable OutageClass = "unreadable" // "The file cannot be read."
	OutageKey        OutageClass = "key"        // "The key file is missing or does not match this accounts file."
	OutageUnwritable OutageClass = "unwritable" // "The file cannot be written. Free space on its disk."
)

The outage classes, each with the one sentence the page writes for it.

type OutageCommand

type OutageCommand struct {
	Run  string // required: "docker exec seadex-scout seadex-scout accounts restore <archive>"
	Note string // "" draws none
}

OutageCommand is one command line that recovers the files, as run in the container, and the note the page draws under it.

type OutageConfig

type OutageConfig struct {
	Assets    fs.FS           // the bundle; its style entry styles the page when built
	Errors    ErrorResponder  // answers under APIPrefix and for a refused method; nil is WriteError
	Style     string          // the style entry's logical name ("app.css"); "" is unstyled
	Title     string          // required: "seadex-scout cannot start"
	App       string          // required: the app's name, written into the class sentences
	APIPrefix string          // the API's path prefix ("/api"); the page answers nothing at or under it
	Notice    string          // one line drawn above the commands; "" draws none
	Files     []OutageFile    // each file that cannot open
	Commands  []OutageCommand // the commands that recover the files, in order
	Restart   bool            // the closing line names a container restart instead of a reload
}

OutageConfig configures OutagePage.

type OutageFile

type OutageFile struct {
	Name  string      // required: the file's setting and path as the person knows it ("ACCOUNTS_PATH, /config/accounts.db")
	Class OutageClass // why it cannot open
}

OutageFile is one file that cannot open. The page writes Name and the class's sentence; the error that classed it belongs in the log.

type Page

type Page struct {
	Name    string // the route's name in the TS router, an ASCII identifier
	Pattern string // a ServeMux path pattern with no method and no host: "/library/{id}"
	Shell   string // the shell file at the bundle's root; "" is "index.html"
}

Page is one page of a single-page app: the path pattern it answers and the shell it answers with.

type PageMatch

type PageMatch struct {
	Params   map[string]string // each wildcard's value as Request.PathValue gives it
	Name     string            // the page's Name; "" with a Redirect
	Redirect string            // the path and query ServeMux redirects to; "" on a match
}

PageMatch is one Match answer: a page, or a redirect.

type PageMatcher

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

PageMatcher is SPA's page match. It registers each pattern on an http.ServeMux and serves the request path through it, so the match, the path cleaning and the trailing-slash redirect are ServeMux's own.

func NewPageMatcher

func NewPageMatcher(pages []Page, apiPrefix string) (*PageMatcher, error)

NewPageMatcher builds the matcher for pages, refusing what CheckPages refuses, an apiPrefix that is not a clean path of literal segments with no trailing slash ("/api"), and a page whose pattern's literal part is at or under apiPrefix.

func (*PageMatcher) Match

func (m *PageMatcher) Match(target string) (PageMatch, bool)

Match answers the page target names, or the redirect ServeMux answers it with. target is the escaped path and query as the client sent them. ok is false for a target that does not parse, names no page, redirects to no page, or whose path, decoded or cleaned, is at or under the API prefix.

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". A code outside CodeSpecs carries an empty remediation.

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. Nil, the default, means slog.Default() as it is when the panic is logged.

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

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

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

func WithServeExit

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

WithServeExit registers an opt-in teardown hook Run invokes when srv.Serve returns on its own — before ctx is ever cancelled — in place of the graceful sequence. That covers a fatal serve error (the listener or the accept loop is gone) and a Shutdown or Close the caller drove itself outside Run. Exactly one of the two paths runs per Run call: with the hook registered, either pre-drain -> Shutdown -> 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

func WithShutdownGrace(d time.Duration) RunOption

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

func WithTeardown

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

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 SPAConfig

type SPAConfig struct {
	Assets    fs.FS               // the bundle; nil, or no BundlePath in it, is unbuilt
	CSPAdd    map[string][]string // additions to the default policy; SPAPolicy says which are allowed
	Errors    ErrorResponder      // answers every refusal; nil is WriteError
	Logger    *slog.Logger        // nil is slog.Default()
	APIPrefix string              // the API's path prefix ("/api"); SPA answers nothing at or under it
	Pages     []Page              // the page patterns, each answering its shell
}

SPAConfig configures SPA.

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 Served

type Served struct {
	Server   *http.Server
	Listener net.Listener
	Options  []RunOption
}

Served is a product listener RunWithOps serves with Run and Options.

type ServerOption

type ServerOption func(*http.Server)

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 forward net/http's own connection-level lines, above all "http: Accept error: ...; retrying" (an exhausted fd budget), into slog.Default() at level, resolved as each line is logged. The level is the caller's: an accept failure is fatal to a probe-only service and a degradation to one that retries. Without it, ErrorLog stays net/http's standard logger.

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; WithStaticETags sets the tags. A nil fn keeps the default.

func WithStaticETags

func WithStaticETags(tags map[string]string) StaticOption

WithStaticETags gives each file its entity-tag by path in fsys (no leading slash), each a quoted strong entity-tag such as `"3f2a"`, and StaticHandler then hashes no file. A named file answers its tag and its gzip body the tag plus "-gz"; an unnamed file is served with no ETag, Cache-Control or gzip body. A nil map names no file. StaticHandler refuses a path naming no file and a tag that is not a strong entity-tag (RFC 9110 section 8.8.3).

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/v2"
)

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.

type TokenSet

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

TokenSet matches a presented credential against several configured secrets in constant time and reports which one matched. It is the multi-secret form of StaticTokenVerifier, for an endpoint whose callers each hold their own secret. Build it with NewTokenSet. The zero value matches nothing. It is safe for concurrent use.

func NewTokenSet

func NewTokenSet(configured []string) (TokenSet, error)

NewTokenSet keeps the SHA-256 digest of each configured secret, in order, so Match's index is the secret's position in configured. It refuses no secret at all, an empty secret, one longer than MaxTokenBytes, and one given twice, which would make the index ambiguous, with a *TokenSetError.

func (TokenSet) Len

func (s TokenSet) Len() int

Len reports how many secrets the set holds.

func (TokenSet) Match

func (s TokenSet) Match(presented string) (index int, ok bool)

Match reports the position of the configured secret presented equals. A value longer than MaxTokenBytes answers (-1, false) without being hashed; any other is hashed once and compared with every configured digest, with no early exit, so the time taken depends only on the number of secrets. No match, and the zero TokenSet, answer (-1, false).

type TokenSetError

type TokenSetError struct {
	// Err is one of ErrNoTokens, ErrTokenEmpty, ErrTokenTooLong and
	// ErrTokenRepeated.
	Err error
	// Index is the refused token's position; -1 for ErrNoTokens.
	Index int
	// First is the earlier position a repeated token equals; -1 otherwise.
	First int
}

TokenSetError is NewTokenSet's refusal. It names positions only, never a byte of any secret, so a caller can map Index to its own configuration line without the message quoting a token.

func (*TokenSetError) Error

func (e *TokenSetError) Error() string

func (*TokenSetError) Unwrap

func (e *TokenSetError) Unwrap() error

Directories

Path Synopsis
Package httpservertest holds the test helpers for code built on httpserver.
Package httpservertest holds the test helpers for code built on httpserver.
Package imagecache serves an upstream's images from the app's own origin, checked and kept in a bounded on-disk cache.
Package imagecache serves an upstream's images from the app's own origin, checked and kept in a bounded on-disk cache.
internal
httpfield
Package httpfield parses RFC 9110 list-valued header fields for the httpserver module's packages.
Package httpfield parses RFC 9110 list-valued header fields for the httpserver module's packages.

Jump to

Keyboard shortcuts

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