Help us shape the future of Go! Take the 2026 Go Developer Survey

middleware

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 22 Imported by: 1

Documentation

Overview

Package middleware provides Vukem's built-in net/http middleware. Every constructor returns a func(http.Handler) http.Handler, so they compose with any other middleware. Errors are rendered through web.Fail, which uses the router's error handler (problem+json, HTML or htmx fragments).

Index

Constants

View Source
const DefaultCSP = "default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self' 'nonce-{nonce}'; " +
	"img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; " +
	"frame-ancestors 'none'; form-action 'self'"

DefaultCSP is a strict policy suitable for server-rendered pages with nonce'd scripts and styles.

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

RequestIDHeader is the header carrying the request id.

Variables

This section is empty.

Functions

func CSPNonce

func CSPNonce(ctx context.Context) string

CSPNonce returns the per-request CSP nonce, or "" when SecureHeaders did not run. Templates expose it as {{ cspNonce }}.

Types

type CORSConfig

type CORSConfig struct {
	// AllowedOrigins lists exact origins ("https://app.example.com") or "*".
	AllowedOrigins []string
	// AllowedMethods defaults to GET, HEAD, POST, PUT, PATCH, DELETE.
	AllowedMethods []string
	// AllowedHeaders defaults to Accept, Authorization, Content-Type,
	// X-Requested-With, X-CSRF-Token.
	AllowedHeaders []string
	// ExposedHeaders are readable by the browser.
	ExposedHeaders []string
	// AllowCredentials allows cookies/Authorization; incompatible with "*".
	AllowCredentials bool
	// MaxAge caches preflight responses.
	MaxAge time.Duration
}

CORSConfig configures cross-origin resource sharing. The zero value allows no cross-origin requests (deny by default).

type Middleware

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

Middleware wraps an http.Handler.

func BodyLimit

func BodyLimit(n int64) Middleware

BodyLimit caps request bodies at n bytes; larger bodies fail with 413.

func CORS

func CORS(cfg CORSConfig) (Middleware, error)

CORS returns CORS middleware. Register it as server middleware so preflight requests are answered before routing. It returns an error for insecure configurations ("*" with credentials), so misconfiguration fails at boot (A02).

func Gzip

func Gzip() Middleware

Gzip compresses text-like responses for clients that accept gzip. Bodies smaller than 1 KiB, already-encoded responses, ranges and event streams are passed through.

func JSONOnly

func JSONOnly() Middleware

JSONOnly makes a route group JSON-only: write requests must send JSON (415 otherwise) and errors render as problem+json.

func Logger

func Logger(log *slog.Logger) Middleware

Logger logs one structured line per request (method, path, status, duration, size, request id). 5xx log at ERROR, 4xx at WARN.

func MethodOverride

func MethodOverride() Middleware

MethodOverride lets HTML forms send PUT, PATCH and DELETE through a hidden "_method" field on POST. Register it as server middleware so routing sees the overridden method.

func Recover

func Recover() Middleware

Recover converts panics into 500 responses rendered by the error handler and logs the stack trace server-side only (A10). http.ErrAbortHandler is re-raised so net/http can abort the connection.

func RequestID

func RequestID() Middleware

RequestID reuses a well-formed incoming X-Request-ID or generates one, stores it in the context (web.RequestID) and echoes it in the response.

func SecureHeaders

func SecureHeaders(cfg SecureHeadersConfig) Middleware

SecureHeaders sets security headers on every response (A02).

func Static

func Static(root *os.Root, cfg StaticConfig) Middleware

Static serves files from root when they exist and passes other requests on. Files are opened through os.Root, so ".." and symlinks cannot escape the directory (A01); dotfiles and directory listings are never served. The caller owns root and closes it on shutdown.

func StaticFS

func StaticFS(fsys fs.FS, cfg StaticConfig) Middleware

StaticFS is Static over any fs.FS (e.g. an embed.FS in production).

func Timeout

func Timeout(d time.Duration) Middleware

Timeout sets a deadline on the request context. Handlers and queries that respect the context stop when it expires.

type SecureHeadersConfig

type SecureHeadersConfig struct {
	// CSP is the Content-Security-Policy; "{nonce}" is replaced with a
	// per-request nonce. Empty uses DefaultCSP; "-" disables the header.
	CSP string
	// HSTSMaxAge enables Strict-Transport-Security on HTTPS requests.
	// Zero uses two years; negative disables it.
	HSTSMaxAge time.Duration
	// FrameOptions defaults to DENY; "-" disables it.
	FrameOptions string
	// ReferrerPolicy defaults to strict-origin-when-cross-origin.
	ReferrerPolicy string
	// PermissionsPolicy defaults to camera=(), microphone=(), geolocation=().
	PermissionsPolicy string
	// TrustForwardedProto treats X-Forwarded-Proto: https as HTTPS (set it
	// only behind a trusted proxy).
	TrustForwardedProto bool
}

SecureHeadersConfig configures SecureHeaders. Zero values use the secure defaults documented in docs/security.md.

type StaticConfig

type StaticConfig struct {
	// Prefix is the URL prefix ("/" serves files at the root).
	Prefix string
	// ImmutablePrefixes get a one-year immutable cache (hashed build output).
	ImmutablePrefixes []string
}

StaticConfig configures Static.

Jump to

Keyboard shortcuts

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