middleware

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware for the Helix framework.

Index

Constants

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

RequestIDHeader is the default header name for the request ID.

Variables

This section is empty.

Functions

func ETagFromContent

func ETagFromContent(content []byte, weak bool) string

ETagFromContent generates an ETag from content.

func ETagFromString

func ETagFromString(s string, weak bool) string

ETagFromString generates an ETag from a string.

func ETagFromVersion

func ETagFromVersion(version int64, weak bool) string

ETagFromVersion generates an ETag from a version number.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from the context. Returns an empty string if no request ID is set.

func GetRequestIDFromRequest

func GetRequestIDFromRequest(r *http.Request) string

GetRequestIDFromRequest retrieves the request ID from the request context.

func SetCacheControl

func SetCacheControl(w http.ResponseWriter, value string)

SetCacheControl sets the Cache-Control header on the response.

func SetExpires

func SetExpires(w http.ResponseWriter, t time.Time)

SetExpires sets the Expires header on the response.

func SetLastModified

func SetLastModified(w http.ResponseWriter, t time.Time)

SetLastModified sets the Last-Modified header on the response.

Types

type BasicAuthConfig

type BasicAuthConfig struct {
	// Validator is a function that validates the username and password.
	// Return true if the credentials are valid.
	Validator func(username, password string) bool

	// Realm is the authentication realm displayed in the browser.
	// Default: "Restricted"
	Realm string

	// SkipFunc determines if authentication should be skipped.
	SkipFunc func(r *http.Request) bool
}

BasicAuthConfig configures the BasicAuth middleware.

type CORSConfig

type CORSConfig struct {
	// AllowOrigins is a list of origins that are allowed.
	// Use "*" to allow all origins.
	// Default: []
	AllowOrigins []string

	// AllowOriginFunc is a custom function to validate the origin.
	// If set, AllowOrigins is ignored.
	AllowOriginFunc func(origin string) bool

	// AllowMethods is a list of methods that are allowed.
	// Default: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
	AllowMethods []string

	// AllowHeaders is a list of headers that are allowed.
	// Default: Origin, Content-Type, Accept, Authorization
	AllowHeaders []string

	// ExposeHeaders is a list of headers that are exposed to the client.
	// Default: []
	ExposeHeaders []string

	// AllowCredentials indicates whether credentials are allowed.
	// Default: false
	AllowCredentials bool

	// MaxAge is the maximum age (in seconds) of the preflight cache.
	// Default: 0 (no caching)
	MaxAge int
}

CORSConfig configures the CORS middleware.

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig returns the default CORS configuration.

type CacheConfig

type CacheConfig struct {
	// MaxAge sets the max-age directive in seconds.
	// Default: 0 (not set)
	MaxAge int

	// SMaxAge sets the s-maxage directive in seconds (for shared caches).
	// Default: 0 (not set)
	SMaxAge int

	// Public indicates the response can be cached by any cache.
	// Default: false
	Public bool

	// Private indicates the response is for a single user.
	// Default: false
	Private bool

	// NoCache indicates the response must be revalidated before use.
	// Default: false
	NoCache bool

	// NoStore indicates the response must not be stored.
	// Default: false
	NoStore bool

	// NoTransform indicates the response must not be transformed.
	// Default: false
	NoTransform bool

	// MustRevalidate indicates stale responses must be revalidated.
	// Default: false
	MustRevalidate bool

	// ProxyRevalidate is like MustRevalidate but for shared caches.
	// Default: false
	ProxyRevalidate bool

	// Immutable indicates the response body will not change.
	// Default: false
	Immutable bool

	// StaleWhileRevalidate allows serving stale content while revalidating.
	// Value is in seconds.
	// Default: 0 (not set)
	StaleWhileRevalidate int

	// StaleIfError allows serving stale content if there's an error.
	// Value is in seconds.
	// Default: 0 (not set)
	StaleIfError int

	// SkipFunc determines if cache headers should be skipped.
	SkipFunc func(r *http.Request) bool

	// VaryHeaders is a list of headers to include in the Vary header.
	VaryHeaders []string
}

CacheConfig configures the Cache middleware.

func DefaultCacheConfig

func DefaultCacheConfig() CacheConfig

DefaultCacheConfig returns the default Cache configuration.

type CompressConfig

type CompressConfig struct {
	// Level is the compression level.
	// Valid levels: -1 (default), 0 (no compression), 1 (best speed) to 9 (best compression)
	// Default: -1 (gzip.DefaultCompression)
	Level int

	// MinSize is the minimum size in bytes to trigger compression.
	// Default: 1024 (1KB)
	MinSize int

	// Types is a list of content types to compress.
	// Default: text/*, application/json, application/javascript, application/xml
	Types []string

	// SkipFunc is a function that determines if compression should be skipped.
	SkipFunc func(r *http.Request) bool
}

CompressConfig configures the Compress middleware.

func DefaultCompressConfig

func DefaultCompressConfig() CompressConfig

DefaultCompressConfig returns the default Compress configuration.

type ETagConfig

type ETagConfig struct {
	// Weak indicates whether to generate weak ETags.
	// Weak ETags are prefixed with W/ and indicate semantic equivalence.
	// Default: false (strong ETags)
	Weak bool

	// SkipFunc determines if ETag generation should be skipped.
	SkipFunc func(r *http.Request) bool
}

ETagConfig configures the ETag middleware.

func DefaultETagConfig

func DefaultETagConfig() ETagConfig

DefaultETagConfig returns the default ETag configuration.

type LogEntry

type LogEntry struct {
	Timestamp    string            `json:"timestamp"`
	Method       string            `json:"method"`
	Path         string            `json:"path"`
	URL          string            `json:"url,omitempty"`
	Status       int               `json:"status"`
	Latency      string            `json:"latency"`
	LatencyMs    float64           `json:"latency_ms"`
	Size         int               `json:"size"`
	RemoteAddr   string            `json:"remote_addr"`
	UserAgent    string            `json:"user_agent,omitempty"`
	Referer      string            `json:"referer,omitempty"`
	RequestID    string            `json:"request_id,omitempty"`
	Error        string            `json:"error,omitempty"`
	CustomFields map[string]string `json:"custom,omitempty"`
}

LogEntry represents a JSON log entry.

type LogFormat

type LogFormat string

LogFormat represents a predefined log format.

const (
	// LogFormatCombined is the Apache combined log format.
	// :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res-length ":referrer" ":user-agent"
	LogFormatCombined LogFormat = "combined"

	// LogFormatCommon is the Apache common log format.
	// :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res-length
	LogFormatCommon LogFormat = "common"

	// LogFormatDev is a colorized development format.
	// :method :url :status :response-time ms - :res-length
	LogFormatDev LogFormat = "dev"

	// LogFormatShort is a shorter format.
	// :remote-addr :method :url HTTP/:http-version :status :res-length - :response-time ms
	LogFormatShort LogFormat = "short"

	// LogFormatTiny is the minimal format.
	// :method :url :status :res-length - :response-time ms
	LogFormatTiny LogFormat = "tiny"

	// LogFormatJSON outputs logs in JSON format.
	LogFormatJSON LogFormat = "json"
)

Predefined log formats matching Morgan.js formats.

type LoggerConfig

type LoggerConfig struct {
	// Format is the log format to use.
	// Default: LogFormatDev
	Format LogFormat

	// CustomFormat is a custom format string using tokens.
	// If set, Format is ignored (unless Format is LogFormatJSON).
	CustomFormat string

	// Output is the writer to output logs to.
	// Default: os.Stdout
	Output io.Writer

	// Skip is a function that determines if logging should be skipped.
	// If it returns true, the request is not logged.
	Skip func(r *http.Request) bool

	// TimeFormat is the time format for the :date token.
	// Default: time.RFC1123
	TimeFormat string

	// Fields maps custom field names to their sources.
	// Sources can be:
	//   - "header:X-Header-Name" - extracts from request header
	//   - "query:param_name" - extracts from query parameter
	//   - "cookie:cookie_name" - extracts from cookie
	// Example: {"api_version": "header:X-API-Version", "page": "query:page"}
	Fields map[string]string

	// CustomTokens maps token names to extractor functions.
	// These can extract data from the request body or perform custom logic.
	// Token names should not include the leading colon.
	// Example: {"user_id": func(r, body) string { ... }}
	CustomTokens map[string]TokenExtractor

	// CaptureBody enables capturing the request body for custom token extraction.
	// When enabled, the request body is read and stored for token extractors.
	// Default: false (only enable if you need body-based custom tokens)
	CaptureBody bool

	// MaxBodySize is the maximum size of the request body to capture.
	// Default: 64KB
	MaxBodySize int64

	// JSONFields specifies which fields to include in JSON output.
	// If empty, a default set of fields is used.
	// Fields can be standard tokens (without colon) or custom field names.
	JSONFields []string

	// JSONPretty enables pretty-printing for JSON output.
	// Default: false
	JSONPretty bool

	// DisableColors disables ANSI color codes in output.
	// Default: false
	DisableColors bool
}

LoggerConfig configures the Logger middleware.

func DefaultLoggerConfig

func DefaultLoggerConfig() LoggerConfig

DefaultLoggerConfig returns the default configuration for Logger.

type Middleware

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

Middleware is a function that wraps an http.Handler to provide additional functionality.

func API

func API() []Middleware

API returns a middleware bundle suitable for JSON API servers. Includes: RequestID, Logger (JSON format), Recover, and CORS.

func APIWithCORS

func APIWithCORS(cors CORSConfig) []Middleware

APIWithCORS returns a middleware bundle suitable for JSON API servers with a custom CORS configuration. Includes: RequestID, Logger (JSON format), Recover, and CORS with config.

func BasicAuth

func BasicAuth(username, password string) Middleware

BasicAuth returns a BasicAuth middleware with the given username and password. Uses constant-time comparison to prevent timing attacks.

func BasicAuthUsers

func BasicAuthUsers(users map[string]string) Middleware

BasicAuthUsers returns a BasicAuth middleware that validates against a map of users. The map key is the username and the value is the password.

func BasicAuthWithConfig

func BasicAuthWithConfig(config BasicAuthConfig) Middleware

BasicAuthWithConfig returns a BasicAuth middleware with the given configuration.

func BasicAuthWithValidator

func BasicAuthWithValidator(validator func(username, password string) bool) Middleware

BasicAuthWithValidator returns a BasicAuth middleware with a custom validator.

func CORS

func CORS() Middleware

CORS returns a CORS middleware with default configuration.

func CORSAllowAll

func CORSAllowAll() Middleware

CORSAllowAll returns a CORS middleware that allows all origins, methods, and headers.

func CORSWithConfig

func CORSWithConfig(config CORSConfig) Middleware

CORSWithConfig returns a CORS middleware with the given configuration.

func Cache

func Cache(maxAge int) Middleware

Cache returns a Cache middleware with the given max-age in seconds.

func CacheImmutable

func CacheImmutable(maxAge int) Middleware

CacheImmutable returns a Cache middleware for immutable content.

func CachePrivate

func CachePrivate(maxAge int) Middleware

CachePrivate returns a Cache middleware with private caching.

func CachePublic

func CachePublic(maxAge int) Middleware

CachePublic returns a Cache middleware with public caching.

func CacheWithConfig

func CacheWithConfig(config CacheConfig) Middleware

CacheWithConfig returns a Cache middleware with the given configuration.

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain creates a new middleware chain from the given middlewares. The first middleware in the chain is the outermost (executed first on request, last on response).

func Compress

func Compress() Middleware

Compress returns a middleware that compresses responses using gzip or deflate.

func CompressWithConfig

func CompressWithConfig(config CompressConfig) Middleware

CompressWithConfig returns a Compress middleware with the given configuration.

func CompressWithLevel

func CompressWithLevel(level int) Middleware

CompressWithLevel returns a Compress middleware with the given compression level.

func Development

func Development() []Middleware

Development returns a middleware bundle suitable for development. Includes: RequestID, Logger (dev format), Recover. This is the same as what helix.Default() uses.

func ETag

func ETag() Middleware

ETag returns an ETag middleware with default configuration.

func ETagWeak

func ETagWeak() Middleware

ETagWeak returns an ETag middleware that generates weak ETags.

func ETagWithConfig

func ETagWithConfig(config ETagConfig) Middleware

ETagWithConfig returns an ETag middleware with the given configuration.

func Logger

func Logger(format LogFormat) Middleware

Logger returns a middleware that logs HTTP requests. Uses the dev format by default.

func LoggerJSON

func LoggerJSON() Middleware

LoggerJSON returns a middleware that logs HTTP requests in JSON format.

func LoggerWithConfig

func LoggerWithConfig(config LoggerConfig) Middleware

LoggerWithConfig returns a Logger middleware with the given configuration.

func LoggerWithFields

func LoggerWithFields(fields map[string]string) Middleware

LoggerWithFields returns a Logger middleware with custom fields.

func LoggerWithFormat

func LoggerWithFormat(format string) Middleware

LoggerWithFormat returns a Logger middleware with a custom format string.

func Minimal

func Minimal() []Middleware

Minimal returns a minimal middleware bundle with only essential middleware. Includes: Recover.

func NoCache

func NoCache() Middleware

NoCache returns a middleware that disables caching.

func Production

func Production() []Middleware

Production returns a middleware bundle suitable for production environments. Includes: RequestID, Logger (combined format), Recover.

func RateLimit

func RateLimit(rate float64, burst int) Middleware

RateLimit returns a rate limiting middleware with the given rate and burst.

func RateLimitWithConfig

func RateLimitWithConfig(config RateLimitConfig) Middleware

RateLimitWithConfig returns a RateLimit middleware with the given configuration.

func Recover

func Recover() Middleware

Recover returns a middleware that recovers from panics. It logs the panic and stack trace, then returns a 500 Internal Server Error.

func RecoverWithConfig

func RecoverWithConfig(config RecoverConfig) Middleware

RecoverWithConfig returns a Recover middleware with the given configuration.

func RequestID

func RequestID() Middleware

RequestID returns a middleware that generates or propagates a request ID. The request ID is stored in the request context and the response header.

func RequestIDWithConfig

func RequestIDWithConfig(config RequestIDConfig) Middleware

RequestIDWithConfig returns a RequestID middleware with the given configuration.

func Secure

func Secure(rate float64, burst int) []Middleware

Secure returns a middleware bundle with security-focused middleware. Includes: RequestID, Logger (JSON format), Recover, RateLimit. Note: You should also add CORS and authentication middleware as needed. Parameters:

  • rate: requests per second allowed
  • burst: maximum burst size

func Timeout

func Timeout(timeout time.Duration) Middleware

Timeout returns a middleware that adds a timeout to requests.

func TimeoutWithConfig

func TimeoutWithConfig(config TimeoutConfig) Middleware

TimeoutWithConfig returns a Timeout middleware with the given configuration.

func Web

func Web() []Middleware

Web returns a middleware bundle suitable for web applications. Includes: RequestID, Logger (dev format), Recover, and Compress.

type RateLimitConfig

type RateLimitConfig struct {
	// Rate is the number of requests allowed per second.
	// Default: 100
	Rate float64

	// Burst is the maximum number of requests allowed in a burst.
	// Default: 10
	Burst int

	// KeyFunc extracts the rate limit key from the request.
	// Default: uses client IP address
	KeyFunc func(r *http.Request) string

	// Handler is called when the rate limit is exceeded.
	// If nil, a default 429 Too Many Requests response is sent.
	Handler http.HandlerFunc

	// SkipFunc determines if rate limiting should be skipped.
	SkipFunc func(r *http.Request) bool

	// CleanupInterval is the interval for cleaning up expired entries.
	// Default: 1 minute
	CleanupInterval time.Duration

	// ExpirationTime is how long to keep entries after last access.
	// Default: 5 minutes
	ExpirationTime time.Duration
}

RateLimitConfig configures the RateLimit middleware.

func DefaultRateLimitConfig

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns the default RateLimit configuration.

type RecoverConfig

type RecoverConfig struct {
	// PrintStack enables printing the stack trace when a panic occurs.
	// Default: true
	PrintStack bool

	// StackSize is the maximum size of the stack trace buffer.
	// Default: 4KB
	StackSize int

	// Output is the writer to output the panic message to.
	// Default: os.Stderr
	Output io.Writer

	// Handler is a custom function to handle panics.
	// If set, it will be called instead of the default behavior.
	// The handler should write the response and return.
	Handler func(w http.ResponseWriter, r *http.Request, err any)
}

RecoverConfig configures the Recover middleware.

func DefaultRecoverConfig

func DefaultRecoverConfig() RecoverConfig

DefaultRecoverConfig returns the default configuration for Recover.

type RequestIDConfig

type RequestIDConfig struct {
	// Header is the name of the header to read/write the request ID.
	// Default: "X-Request-ID"
	Header string

	// Generator is a function that generates a new request ID.
	// Default: generates a random 16-byte hex string
	Generator func() string

	// TargetHeader is the header name to set on the response.
	// Default: same as Header
	TargetHeader string
}

RequestIDConfig configures the RequestID middleware.

func DefaultRequestIDConfig

func DefaultRequestIDConfig() RequestIDConfig

DefaultRequestIDConfig returns the default configuration for RequestID.

type TimeoutConfig

type TimeoutConfig struct {
	// Timeout is the maximum duration for the request.
	// Default: 30 seconds
	Timeout time.Duration

	// Handler is called when the request times out.
	// If nil, a default 503 Service Unavailable response is sent.
	Handler http.HandlerFunc

	// SkipFunc is a function that determines if timeout should be skipped.
	// If it returns true, no timeout is applied.
	SkipFunc func(r *http.Request) bool
}

TimeoutConfig configures the Timeout middleware.

func DefaultTimeoutConfig

func DefaultTimeoutConfig() TimeoutConfig

DefaultTimeoutConfig returns the default Timeout configuration.

type TokenExtractor

type TokenExtractor func(r *http.Request, body []byte) string

TokenExtractor is a function that extracts a value from the request. It receives the request and the captured request body (if body capture is enabled).

func ContextValueExtractor

func ContextValueExtractor(key any) TokenExtractor

ContextValueExtractor creates a token extractor that extracts a value from request context.

func FormValueExtractor

func FormValueExtractor(field string) TokenExtractor

FormValueExtractor creates a token extractor that extracts a form field.

func JSONBodyExtractor

func JSONBodyExtractor(path string) TokenExtractor

JSONBodyExtractor creates a token extractor that extracts a field from JSON body. The path can be a simple field name like "user_id" or a nested path like "user.id".

Jump to

Keyboard shortcuts

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