middleware

package
v1.1.20 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package middleware provides a standard approach for chaining and composing HTTP middleware.

Usage

The core type is Pipe, an adapter that wraps an http.Handler to add functionality. The Chain function composes these pipes into a single handler. The package also includes common middleware like Recover for panic handling, RequestID for tracing, and Log for request logging.

Example:

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("OK"))
})

// Chain middleware around the final handler.
// Order matters: Recover must be first (outermost).
logger := slog.Default()
chainedHandler := middleware.Chain(handler,
	middleware.Recover(logger),
	middleware.RequestID(),
	middleware.Log(logger),
)

http.ListenAndServe(":8080", chainedHandler)

Index

Constants

This section is empty.

Variables

View Source
var DefaultSecurityConfig = SecurityConfig{
	STSMaxAge:               31536000,
	STSIncludeSubdomains:    true,
	FrameOptions:            "DENY",
	NoSniff:                 true,
	PermissionsPolicy:       "geolocation=(), microphone=(), camera=(), payment=()",
	CrossOriginOpenerPolicy: "same-origin",
}

DefaultSecurityConfig provides a baseline configuration that enables HSTS for 1 year, disables MIME sniffing, and protects against clickjacking by denying framing.

Functions

func Chain

func Chain(h http.Handler, pipes ...Pipe) http.Handler

Chain combines a handler with multiple middleware Pipes. The pipes are applied in reverse order, meaning the first pipe in the list is the outermost and executes first.

For example, Chain(h, A, B, C) results in a handler equivalent to A(B(C(h))). Any nil pipes in the list are safely ignored.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from a given context. It returns an empty string if the ID is not found.

func SetRequestID

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

SetRequestID sets the request ID in the provided context, returning a new context that carries the ID.

Types

type Pipe

type Pipe func(http.Handler) http.Handler

Pipe is a middleware function. It's an adapter that takes an http.Handler and returns a new http.Handler, allowing functionality to be composed in layers.

func Log

func Log(logger *slog.Logger) Pipe

Log returns a middleware Pipe that logs a summary of each HTTP request. It captures the final HTTP status code by wrapping the http.ResponseWriter.

The log entry is generated at the debug level after the request has been handled. It includes the method, URL, status code, duration, and other common attributes. To include a request ID in the log, this middleware should be placed after the RequestID middleware in the chain.

func Recover

func Recover(logger *slog.Logger) Pipe

Recover produces a middleware Pipe that catches panics in downstream handlers. It uses the provided logger to report the exception with a stack trace and returns an empty response with status code 500 to the client. The log entry also pinpoints the request method and URL that caused the panic. For maximum effectiveness, this should be the first (outermost) middleware in the chain.

func RequestID

func RequestID() Pipe

RequestID returns a middleware Pipe that injects a unique ID into each request. It adds the ID to the response via the "X-Request-ID" header and to the request's context for downstream use.

Downstream handlers and other middleware can retrieve the ID using GetRequestID. If a unique ID cannot be generated from the random source, this middleware does nothing and passes the request to the next handler.

func Secure added in v1.1.2

func Secure(cfg SecurityConfig) Pipe

Secure returns a middleware Pipe that sets various security-related HTTP headers based on the provided configuration.

func Volatile added in v1.1.2

func Volatile() Pipe

Volatile returns a middleware Pipe that prevents caching of the response. It sets standard HTTP headers (Cache-Control, Pragma, Expires) to ensure clients and proxies always fetch a fresh copy of the resource.

type SecurityConfig added in v1.1.2

type SecurityConfig struct {
	// STSMaxAge is the maximum age for HSTS in seconds.
	// If 0, the header is not set.
	STSMaxAge int64
	// STSIncludeSubdomains adds the "includeSubDomains" directive to HSTS.
	STSIncludeSubdomains bool
	// FrameOptions sets the X-Frame-Options header (e.g., "DENY", "SAMEORIGIN").
	// If empty, the header is not set.
	FrameOptions string
	// NoSniff sets X-Content-Type-Options to "nosniff" if true.
	// This helps prevent MIME type sniffing by browsers.
	NoSniff bool
	// CSP sets the Content-Security-Policy header.
	// If empty, it is not set.
	CSP string
	// ReferrerPolicy sets the Referrer-Policy header.
	// If empty, it is not set.
	ReferrerPolicy string
	// PermissionsPolicy sets the Permissions-Policy header.
	// Example: "geolocation=(), microphone=()"
	PermissionsPolicy string
	// CrossOriginOpenerPolicy sets the Cross-Origin-Opener-Policy header.
	// Recommended: "same-origin"
	CrossOriginOpenerPolicy string
}

SecurityConfig defines the headers applied by the Secure middleware.

Directories

Path Synopsis
Package cors provides a configurable CORS (Cross-Origin Resource Sharing) middleware for http.Handlers.
Package cors provides a configurable CORS (Cross-Origin Resource Sharing) middleware for http.Handlers.
Package gzip provides an HTTP middleware for compressing response bodies using the gzip algorithm.
Package gzip provides an HTTP middleware for compressing response bodies using the gzip algorithm.

Jump to

Keyboard shortcuts

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