middleware

package
v0.0.0-20260608 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const SessionKey = contextKey("session")

Variables

This section is empty.

Functions

func AddHeaders

func AddHeaders(headers map[string]string) func(http.Handler) http.Handler

AddHeaders adds custom headers to the response

func AddRequestId

func AddRequestId(next http.Handler) http.Handler

AddRequestId adds a request ID to the response.

func Authenticate

func Authenticate(manager *auth.Manager, guardName string) func(http.Handler) http.Handler

Authenticate returns a middleware that checks if the user is authenticated via the specified guard.

func AuthenticateSanctum

func AuthenticateSanctum(next http.Handler) http.Handler

AuthenticateSanctum authenticates Sanctum tokens.

func Authorize

func Authorize(gate *access.Gate, ability string) func(http.Handler) http.Handler

Authorize returns a middleware that checks if the authenticated user has the specified ability via the Gate. If the ability check requires models, they must be passed or resolved (this is a simplified implementation that only checks abilities without models, or abilities where the model can be resolved later, e.g. via Route Model Binding).

func CacheFor

func CacheFor(seconds int) func(http.Handler) http.Handler

CacheFor sets Cache-Control with a max-age directive. Usage: CacheFor(3600) caches for 1 hour.

func CachePrivate

func CachePrivate(seconds int) func(http.Handler) http.Handler

CachePrivate sets Cache-Control to private with a max-age.

func CheckForMaintenanceMode

func CheckForMaintenanceMode(basePath string) func(http.Handler) http.Handler

CheckForMaintenanceMode middleware returns a 503 Service Unavailable if the app is down.

func ConfirmPassword

func ConfirmPassword(next http.Handler) http.Handler

ConfirmPassword requires password confirmation.

func ConvertEmptyStringsToNull

func ConvertEmptyStringsToNull(next http.Handler) http.Handler

ConvertEmptyStringsToNull middleware converts empty string form values to nil. This matches Laravel's ConvertEmptyStringsToNull middleware behavior.

func Cors

func Cors(config CorsConfig) func(http.Handler) http.Handler

Cors handles Cross-Origin Resource Sharing.

func CsrfTokenFromContext

func CsrfTokenFromContext(r *http.Request) string

CsrfTokenFromContext retrieves the CSRF token from the request context.

func EncryptCookies

func EncryptCookies(manager *cookie.Manager, except []string) func(http.Handler) http.Handler

EncryptCookies middleware automatically decrypts incoming cookies and provides a hook (or relies on the cookie manager) for outgoing cookies.

func ErrorHandler

func ErrorHandler(debugMode bool) func(http.Handler) http.Handler

ErrorHandler recovers from panics and converts them to HTTP responses. It handles HttpException natively, and converts other panics into 500s.

func GetSession

func GetSession(r *http.Request) *session.Manager

GetSession is a helper to extract the session from the request context.

func HandlePanic

func HandlePanic(next http.Handler) http.Handler

HandlePanic handles panics.

func LogRequests

func LogRequests(next http.Handler) http.Handler

LogRequests logs incoming requests.

func MonitorMiddleware

func MonitorMiddleware(config ...MonitorConfig) func(http.Handler) http.Handler

MonitorMiddleware returns middleware that serves a monitoring dashboard.

func PermissionMiddleware

func PermissionMiddleware(permission string) func(http.Handler) http.Handler

PermissionMiddleware checks if the user has a specific permission.

func PreloadLinks(preloads map[string]string) func(http.Handler) http.Handler

PreloadLinks sends Link headers for preloading resources

func PreventBackslash

func PreventBackslash(next http.Handler) http.Handler

PreventBackslash prevents URLs with trailing slashes from being redirected

func PreventCache

func PreventCache(next http.Handler) http.Handler

PreventCache is a convenience middleware that sets headers to prevent caching.

func PreventHTTPOnly

func PreventHTTPOnly(next http.Handler) http.Handler

PreventHTTPOnly ensures cookies are not accessible via JavaScript

func PreventHostHeaderAttack

func PreventHostHeaderAttack(allowedHosts []string) func(http.Handler) http.Handler

PreventHostHeaderAttack prevents host header attacks

func PreventLazyLoading

func PreventLazyLoading(next http.Handler) http.Handler

PreventLazyLoading prevents lazy loading of resources

func PreventRequestsDuringMaintenance

func PreventRequestsDuringMaintenance(maintenanceFunc func() bool) func(http.Handler) http.Handler

PreventRequestsDuringMaintenance returns middleware that prevents requests during maintenance mode

func Recovery

func Recovery() func(http.Handler) http.Handler

Recovery returns a middleware that recovers from panics. If the panic is an HttpException, it returns the appropriate HTTP status. Otherwise, it returns a 500 Internal Server Error.

func RoleMiddleware

func RoleMiddleware(role string) func(http.Handler) http.Handler

RoleMiddleware checks if the authenticated user has the required role.

func SecurityHeaders

func SecurityHeaders() func(http.Handler) http.Handler

SecurityHeaders injects standard secure HTTP headers into the response.

func SetCacheHeaders

func SetCacheHeaders(directives string) func(http.Handler) http.Handler

SetCacheHeaders sets HTTP cache control headers on the response. Usage: SetCacheHeaders("private, max-age=3600") or SetCacheHeaders("no-store, no-cache")

func SetCacheHeadersWithMap

func SetCacheHeadersWithMap(headers map[string]string) func(http.Handler) http.Handler

SetCacheHeadersWithMap sets HTTP cache control headers from a map. Usage: SetCacheHeadersWithMap(map[string]string{"Cache-Control": "max-age=3600", "ETag": "\"abc123\""})

func SetMiddlewareHeaders

func SetMiddlewareHeaders(next http.Handler) http.Handler

SetMiddlewareHeaders sets common middleware headers.

func SetSecurityHeaders

func SetSecurityHeaders(next http.Handler) http.Handler

SetSecurityHeaders sets common security headers

func SetTimeout

func SetTimeout(timeout int) func(http.Handler) http.Handler

SetTimeout sets a timeout for the request

func StartSession

func StartSession(store session.Store) func(http.Handler) http.Handler

StartSession initializes the session for the request.

func SubstituteBindings

func SubstituteBindings(next http.Handler) http.Handler

SubstituteBindings substitutes route bindings.

func Throttle

func Throttle(maxAttempts, decayMinutes int) func(http.Handler) http.Handler

Throttle is a convenience wrapper for simple "throttle:60,1" style (max, decayMinutes). Uses a shared package-level rate limiter so all routes share the same rate limit state.

func ThrottleNamed

func ThrottleNamed(name string, maxAttempts, decayMinutes int) func(http.Handler) http.Handler

ThrottleNamed allows "throttle:login:5,1" style named limiters.

func ThrottleRequests

func ThrottleRequests(limiter *cache.RateLimiter, maxAttempts int, decayMinutes int, name ...string) func(http.Handler) http.Handler

ThrottleRequests limits requests. Supports named limiters via key prefix.

func TrimAndConvertEmptyToNull

func TrimAndConvertEmptyToNull(next http.Handler) http.Handler

TrimAndConvertEmptyToNull combines TrimStrings and ConvertEmptyStringsToNull. This is the typical middleware stack used in Laravel's web middleware group.

func TrimStrings

func TrimStrings(next http.Handler) http.Handler

TrimStrings middleware trims whitespace from incoming string parameters. Handles URL query parameters, x-www-form-urlencoded, and multipart/form-data bodies.

func TrustHostsMiddleware

func TrustHostsMiddleware(trustedHosts ...string) func(http.Handler) http.Handler

TrustHostsMiddleware validates that the request Host header matches trusted hosts. If no trusted hosts are configured, all hosts are allowed.

func TrustProxies

func TrustProxies(proxies []string) func(http.Handler) http.Handler

TrustProxies trusts proxy headers.

func ValidatePostSize

func ValidatePostSize(maxSize int64) func(http.Handler) http.Handler

ValidatePostSize validates that the request's Content-Length does not exceed the maximum allowed size (in bytes). Returns 413 Payload Too Large if exceeded.

func ValidateSignature

func ValidateSignature(generator *routing.URLGenerator) func(http.Handler) http.Handler

ValidateSignature is a middleware that requires the request to have a valid signed URL signature. Use with routes that were generated via SignedRoute or TemporarySignedRoute.

func VerifyCsrfToken

func VerifyCsrfToken(opts ...CsrfOptions) func(http.Handler) http.Handler

VerifyCsrfToken validates the CSRF token on mutating requests.

Types

type CorsConfig

type CorsConfig struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	ExposedHeaders   []string
	MaxAge           int
	AllowCredentials bool
}

CorsConfig holds the configuration for CORS middleware.

func DefaultCorsConfig

func DefaultCorsConfig() CorsConfig

DefaultCorsConfig provides a safe default configuration. Note: AllowedOrigins defaults to empty (no cross-origin requests allowed). Set explicit origins or use "*" for development only.

func DevCorsConfig

func DevCorsConfig() CorsConfig

DevCorsConfig provides a permissive configuration for development.

type CsrfOptions

type CsrfOptions struct {
	// URIs is a list of URI prefixes to exclude from CSRF checks (e.g., "/api/").
	URIs []string
}

CsrfOptions configures the CSRF middleware.

type MonitorConfig

type MonitorConfig struct {
	// URI is the endpoint path for the monitor dashboard.
	URI string
	// Title is the title shown on the dashboard.
	Title string
	// RefreshInterval is how often the dashboard refreshes (seconds).
	RefreshInterval int
}

MonitorConfig holds configuration for the monitoring middleware.

func DefaultMonitorConfig

func DefaultMonitorConfig() MonitorConfig

DefaultMonitorConfig returns default monitoring configuration.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides rate limiting functionality

func NewRateLimiter

func NewRateLimiter(limit int, window time.Duration) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (r *RateLimiter) Allow(key string) bool

Allow checks if a request is allowed

func (*RateLimiter) Middleware

func (r *RateLimiter) Middleware(next http.Handler) http.Handler

Middleware returns HTTP middleware for rate limiting

func (*RateLimiter) PerUser

func (r *RateLimiter) PerUser(getUserID func(*http.Request) string) func(http.Handler) http.Handler

PerUser creates a rate limiter that limits per user

type TrustedProxies

type TrustedProxies struct {
	Proxies []string
	Headers []string // e.g. X-Forwarded-For, X-Forwarded-Proto
}

TrustedProxies middleware modifies the request's RemoteAddr to respect X-Forwarded-For headers if the request comes from a trusted proxy.

func NewTrustedProxies

func NewTrustedProxies(proxies []string) *TrustedProxies

NewTrustedProxies creates a new TrustedProxies middleware. If Proxies contains "*", all proxies are trusted.

func (*TrustedProxies) Handle

func (tp *TrustedProxies) Handle(next http.Handler) http.Handler

Handle implements the middleware signature.

Jump to

Keyboard shortcuts

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