middleware

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package middleware provides built-in HTTP middleware for zen (recovery, logging, CORS, CSRF, compression, rate limiting, body limit, pprof).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BodyLimit added in v1.2.0

func BodyLimit(limit any) zen.HandlerFunc

BodyLimit returns middleware that limits request body size.

func BodyLimitWithConfig added in v1.2.0

func BodyLimitWithConfig(config BodyLimitConfig) zen.HandlerFunc

BodyLimitWithConfig returns middleware that limits request body size using a config.

func CORS added in v1.2.0

func CORS(config CORSConfig) zen.HandlerFunc

CORS returns a CORS middleware handler.

func Compress added in v1.2.0

func Compress() zen.HandlerFunc

Compress returns standard gzip compression middleware using default compression parameters.

func CompressWithLevel added in v1.2.0

func CompressWithLevel(level int) zen.HandlerFunc

CompressWithLevel returns compression middleware with a specific gzip level, utilizing isolated sync pools per level to prevent cross-contamination.

func CrossOriginProtection added in v1.2.0

func CrossOriginProtection() zen.HandlerFunc

CrossOriginProtection returns a native CSRF defensive firewall using Go's modern http engine.

func CrossOriginProtectionWithConfig added in v1.2.0

func CrossOriginProtectionWithConfig(config CrossOriginProtectionConfig) zen.HandlerFunc

CrossOriginProtectionWithConfig mounts the Go native CrossOriginProtection middleware.

func GetRequestID added in v1.4.0

func GetRequestID(c *zen.Ctx) string

GetRequestID retrieves the request ID from the context store.

func Logger added in v1.2.0

func Logger(c *zen.Ctx)

Logger logs HTTP requests with method, path, status code, and response time.

func RateLimiter added in v1.2.0

func RateLimiter() zen.HandlerFunc

RateLimiter returns middleware that limits the number of requests per client.

func RateLimiterWithConfig added in v1.2.0

func RateLimiterWithConfig(config RateLimiterConfig) zen.HandlerFunc

RateLimiterWithConfig returns rate limiting middleware.

func Recover

func Recover(c *zen.Ctx)

Recover catches panics, logs the stack trace, and sends a 500 response. Must be registered first (outermost) to catch panics from subsequent handlers.

Example:

r := zen.New(":8080")
r.Use(middleware.Recover) // Must be first
r.Use(middleware.Logger)

func RegisterPprof added in v1.2.0

func RegisterPprof(r *zen.Engine)

RegisterPprof mounts Go's runtime profiling tools directly onto the Zen router. This bypasses intermediate mux wrappers, ensuring compatibility with standard visualization tools like `go tool pprof`.

Example:

r := zen.New()
middleware.RegisterPprof(r)

func RegisterPprofWithConfig added in v1.2.0

func RegisterPprofWithConfig(r *zen.Engine, config PprofConfig)

RegisterPprofWithConfig mounts the profiling toolset using a custom configuration prefix.

func RequestID added in v1.4.0

func RequestID() zen.HandlerFunc

RequestID returns middleware that injects a request ID into the request context and response header. If the client sends a request ID header, it is used as-is; otherwise a new ID is generated.

func RequestIDWithConfig added in v1.4.0

func RequestIDWithConfig(config RequestIDConfig) zen.HandlerFunc

RequestIDWithConfig returns Request ID middleware with the given config.

func Timeout added in v1.4.0

func Timeout(duration time.Duration) zen.HandlerFunc

Timeout returns middleware that cancels requests exceeding the configured duration.

func TimeoutWithConfig added in v1.4.0

func TimeoutWithConfig(config TimeoutConfig) zen.HandlerFunc

TimeoutWithConfig returns timeout middleware with the given config.

It sets a deadline on the request context so context-aware handlers (db queries, HTTP calls) cancel early. Once the deadline passes, the response is marked as timed out: the next write attempt emits a 504 Gateway Timeout and discards the handler's payload, and any subsequent writes are dropped.

Because the handler runs in the request goroutine and the 504 is written by the handler's own write path (or in teardown after it returns), the response writer is never accessed concurrently, and the pooled Ctx can never be reused while the handler is still active.

A handler that blocks forever while ignoring the request context cannot be interrupted; it must return (e.g. by observing ctx.Done()) for the timeout to take effect.

Types

type BodyLimitConfig added in v1.2.0

type BodyLimitConfig struct {
	// Limit can be an int, int64, or a string like "2M", "250K", "1G".
	Limit   any
	Skipper zen.SkipFunc // Optional function to skip body limiting for certain requests.
}

BodyLimitConfig holds configuration for request body size limiting.

func DefaultBodyLimitConfig added in v1.2.0

func DefaultBodyLimitConfig() BodyLimitConfig

DefaultBodyLimitConfig returns a config with a 2MB default limit.

type CORSConfig added in v1.2.0

type CORSConfig struct {
	AllowedOrigins   []string // Origins allowed to make cross-origin requests.
	AllowedMethods   []string // HTTP methods allowed for CORS requests.
	AllowedHeaders   []string // HTTP headers allowed in CORS requests.
	ExposeHeaders    []string // Headers exposed to the client in the response.
	AllowCredentials bool     // Whether to allow credentials (cookies, auth headers).
	MaxAge           int      // Seconds the preflight result can be cached.
}

CORSConfig holds CORS middleware configuration.

func DefaultCORSConfig added in v1.2.0

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig returns a CORSConfig with secure defaults.

type CrossOriginProtectionConfig added in v1.2.0

type CrossOriginProtectionConfig struct {
	Skipper                zen.SkipFunc     // Optional function to skip CSRF checks for certain requests.
	TrustedOrigins         []string         // Origins trusted to make cross-origin requests.
	InsecureBypassPatterns []string         // URL patterns that bypass CSRF protection.
	DenyHandler            func(c *zen.Ctx) // Custom handler invoked when a request is denied.
}

CrossOriginProtectionConfig configures the native Go Cross-Origin CSRF protection.

func DefaultCrossOriginProtectionConfig added in v1.2.0

func DefaultCrossOriginProtectionConfig() CrossOriginProtectionConfig

DefaultCrossOriginProtectionConfig returns an empty configuration structure.

type PprofConfig added in v1.2.0

type PprofConfig struct {
	// Prefix defines the base path for profiling hooks.
	// Default: "/debug/pprof"
	Prefix string
}

PprofConfig holds configuration options for mounting profiling endpoints.

func DefaultPprofConfig added in v1.2.0

func DefaultPprofConfig() PprofConfig

DefaultPprofConfig returns a PprofConfig with sensible defaults.

type RateLimiterConfig added in v1.2.0

type RateLimiterConfig struct {
	Limit    int                        // Maximum number of requests allowed within the Duration.
	Duration time.Duration              // Time window for the rate limit.
	KeyFunc  func(*http.Request) string // Function to extract a unique key per client (default: client IP).
	Skipper  zen.SkipFunc               // Optional function to skip rate limiting for certain requests.
}

RateLimiterConfig holds configuration for rate limiting middleware.

func DefaultRateLimiterConfig added in v1.2.0

func DefaultRateLimiterConfig() RateLimiterConfig

DefaultRateLimiterConfig returns a RateLimiterConfig with sensible defaults.

type RequestIDConfig added in v1.4.0

type RequestIDConfig struct {
	// Header is the request/response header for the request ID.
	// Default: HeaderXRequestID ("X-Request-ID")
	Header string
	// Generator generates a unique request ID. Default: 16-byte hex.
	Generator func() string
	// Skipper optionally skips certain requests.
	Skipper zen.SkipFunc
}

RequestIDConfig holds configuration for the Request ID middleware.

func DefaultRequestIDConfig added in v1.4.0

func DefaultRequestIDConfig() RequestIDConfig

DefaultRequestIDConfig returns a RequestIDConfig with sensible defaults.

type TimeoutConfig added in v1.4.0

type TimeoutConfig struct {
	// Duration is the maximum time a request can take.
	Duration time.Duration

	// Skipper optionally skips certain requests.
	Skipper zen.SkipFunc
}

TimeoutConfig holds configuration for the request timeout middleware.

func DefaultTimeoutConfig added in v1.4.0

func DefaultTimeoutConfig() TimeoutConfig

DefaultTimeoutConfig returns a TimeoutConfig with sensible defaults.

Jump to

Keyboard shortcuts

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