Composable net/http middleware: chain assembly, request matchers, HTTP Basic / API key / HMAC authentication, per-route authorization guards, anonymous authentication, and default security headers (see headers). securityhttp uses these internally — reach for them directly when you want a hand-rolled chain or a guard around a single route.

Import

Chain

Middleware is a type alias for func(http.Handler) http.Handler. Chain composes a list of them and applies them outermost-first — the first one added runs first on the way in and last on the way out.
Chain.Append returns a new chain with more middleware added after the existing ones — handy for a stateless API leg layered on top of a chain built elsewhere (the receiver is untouched):

Request matchers

RequestMatcher is the composable matching interface (Matches(r) bool). MatcherFunc adapts a plain function to it.
Or use the plain functions directly:
Combine matchers with And, Or, Not:
Ant-style wildcards: * matches within a single path segment, ** matches any number of segments (including zero).

Anonymous

Injects an anonymous Authentication on the context when none is present yet, so core.MustAuthentication never panics downstream. A request that already carries an Authentication (from session, Basic, API key, or HMAC auth earlier in the chain) is left untouched.
Anonymous(...) returns a Middleware, so it slots straight into middleware.New(...); called standalone it’s middleware.Anonymous()(handler).

Authorization guards

Per-route guards for a single handler. For whole-app default-deny rules across many routes, see authz instead.
  • RequireAuthenticated() — 401 unless the request carries an authenticated principal.
  • RequireAuthority(authorities...) — 403 unless the principal holds every listed authority (401 if unauthenticated).
  • RequireRole(roles...) — same as RequireAuthority, with each role prefixed ROLE_.

Basic auth

BasicAuth(m *authn.Manager, realm string). No Authorization header passes through unauthenticated (downstream guards decide); a present-but-invalid credential gets a 401 with WWW-Authenticate. Prefer form/session login for browser-facing endpoints — Basic auth is for machine-to-machine calls over HTTPS.

API key

Extractors compose: QueryAPIKeyExtractor("api_key"), FirstAPIKeyExtractor(HeaderAPIKeyExtractor("X-API-Key"), QueryAPIKeyExtractor("api_key")), or pass nil to fall back to DefaultAPIKeyExtractor (header first, then the api_key query param). A missing key passes through unauthenticated; a present-but-invalid key gets a 401.

HMAC signature

For webhook-style clients that sign requests instead of sending a bearer token:
Expects an Authorization: HMAC keyId="...", ts="...", nonce="...", sig="..." header. No header passes through unauthenticated; a malformed header is a 400; an invalid signature is a 401. The body is capped at middleware.HMACMaxBodyBytes (1 MiB) while computing the signature.