middleware

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 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 LogFormat

type LogFormat string

LogFormat represents a predefined log format.

const (
	LogFormatCombined LogFormat = "combined"
	LogFormatCommon   LogFormat = "common"
	LogFormatDev      LogFormat = "dev"
	LogFormatShort    LogFormat = "short"
	LogFormatTiny     LogFormat = "tiny"
	LogFormatJSON     LogFormat = "json"
)

Predefined log formats matching Morgan.js formats.

type LogOutputFunc added in v0.5.0

type LogOutputFunc func(v LogValues)

LogOutputFunc is a callback that receives log values and outputs them. This is the single output mechanism - use helpers for common formats.

func TextOutput added in v0.5.0

func TextOutput(w io.Writer, format LogFormat) LogOutputFunc

TextOutput returns a LogOutputFunc that writes Morgan.js-style formatted logs.

func TextOutputCustom added in v0.5.0

func TextOutputCustom(w io.Writer, format string, opts ...TextOutputOptions) LogOutputFunc

TextOutputCustom returns a LogOutputFunc with a custom format string.

func TextOutputWithOptions added in v0.5.0

func TextOutputWithOptions(w io.Writer, format LogFormat, opts TextOutputOptions) LogOutputFunc

TextOutputWithOptions returns a LogOutputFunc with custom options.

type LogValues added in v0.5.0

type LogValues struct {
	Method        string
	Path          string
	URI           string
	Host          string
	Protocol      string
	RemoteIP      string
	UserAgent     string
	Referer       string
	ContentLength int64
	ContentType   string
	Status        int
	ResponseSize  int
	Latency       time.Duration
	Error         error
	RequestID     string
	StartTime     time.Time
	Headers       map[string]string
	QueryParams   map[string]string
	FormValues    map[string]string
	CustomFields  map[string]string
}

LogValues contains all extracted request/response data for logging.

type LoggerConfig

type LoggerConfig struct {
	// Output is the callback that receives log values. Required.
	// Use TextOutput() for Morgan.js-style formatting.
	// Use helix.StructuredOutput() for logs package integration.
	// Or provide your own function for custom logging.
	Output LogOutputFunc

	// Skip determines if logging should be skipped for a request.
	Skip func(r *http.Request) bool

	// Fields maps custom field names to their sources.
	// Sources: "header:Name", "query:param", "cookie:name"
	Fields map[string]string

	// CustomTokens maps names to extractor functions for body/context data.
	CustomTokens map[string]TokenExtractor

	// LogHeaders specifies request headers to extract into Headers map.
	LogHeaders []string

	// LogQueryParams specifies query parameters to extract.
	LogQueryParams []string

	// LogFormValues specifies form values to extract.
	LogFormValues []string

	// CaptureBody enables request body capture for CustomTokens.
	CaptureBody bool

	// MaxBodySize limits captured body size. Default: 64KB.
	MaxBodySize int64
}

LoggerConfig configures the Logger middleware.

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, Recover, and CORS. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.

func APIWithCORS

func APIWithCORS(cors CORSConfig) []Middleware

APIWithCORS returns a middleware bundle suitable for JSON API servers with a custom CORS configuration. Includes: RequestID, Recover, and CORS with config. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.

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, Recover. Add logging via helix.LoggerMiddleware with your preferred RequestLogger. This is the same as what helix.Default() uses (plus logging).

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() Middleware

Logger returns a middleware with dev format text output.

func LoggerWithConfig

func LoggerWithConfig(config LoggerConfig) Middleware

LoggerWithConfig returns a Logger middleware with the given configuration.

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, Recover. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.

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, Recover, RateLimit. Add logging via helix.LoggerMiddleware with your preferred RequestLogger. 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, Recover, and Compress. Add logging via helix.LoggerMiddleware with your preferred RequestLogger.

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 TextOutputOptions added in v0.5.0

type TextOutputOptions struct {
	TimeFormat    string
	DisableColors bool
	JSONPretty    bool // for LogFormatJSON
}

TextOutputOptions configures text output formatting.

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 extracts a custom value from the request.

func ContextValueExtractor

func ContextValueExtractor(key any) TokenExtractor

ContextValueExtractor creates a TokenExtractor for context values.

func FormValueExtractor

func FormValueExtractor(field string) TokenExtractor

FormValueExtractor creates a TokenExtractor for form fields.

func JSONBodyExtractor

func JSONBodyExtractor(path string) TokenExtractor

JSONBodyExtractor creates a TokenExtractor for JSON body fields.

Jump to

Keyboard shortcuts

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