Documentation
¶
Index ¶
- Constants
- func AddHeaders(headers map[string]string) func(http.Handler) http.Handler
- func AddRequestId(next http.Handler) http.Handler
- func Authenticate(manager *auth.Manager, guardName string) func(http.Handler) http.Handler
- func AuthenticateSanctum(next http.Handler) http.Handler
- func Authorize(gate *access.Gate, ability string) func(http.Handler) http.Handler
- func CacheFor(seconds int) func(http.Handler) http.Handler
- func CachePrivate(seconds int) func(http.Handler) http.Handler
- func CheckForMaintenanceMode(basePath string) func(http.Handler) http.Handler
- func ConfirmPassword(next http.Handler) http.Handler
- func ConvertEmptyStringsToNull(next http.Handler) http.Handler
- func Cors(config CorsConfig) func(http.Handler) http.Handler
- func CsrfTokenFromContext(r *http.Request) string
- func EncryptCookies(manager *cookie.Manager, except []string) func(http.Handler) http.Handler
- func ErrorHandler(debugMode bool) func(http.Handler) http.Handler
- func GetSession(r *http.Request) *session.Manager
- func HandlePanic(next http.Handler) http.Handler
- func LogRequests(next http.Handler) http.Handler
- func MonitorMiddleware(config ...MonitorConfig) func(http.Handler) http.Handler
- func PermissionMiddleware(permission string) func(http.Handler) http.Handler
- func PreloadLinks(preloads map[string]string) func(http.Handler) http.Handler
- func PreventBackslash(next http.Handler) http.Handler
- func PreventCache(next http.Handler) http.Handler
- func PreventHTTPOnly(next http.Handler) http.Handler
- func PreventHostHeaderAttack(allowedHosts []string) func(http.Handler) http.Handler
- func PreventLazyLoading(next http.Handler) http.Handler
- func PreventRequestsDuringMaintenance(maintenanceFunc func() bool) func(http.Handler) http.Handler
- func Recovery() func(http.Handler) http.Handler
- func RoleMiddleware(role string) func(http.Handler) http.Handler
- func SecurityHeaders() func(http.Handler) http.Handler
- func SetCacheHeaders(directives string) func(http.Handler) http.Handler
- func SetCacheHeadersWithMap(headers map[string]string) func(http.Handler) http.Handler
- func SetMiddlewareHeaders(next http.Handler) http.Handler
- func SetSecurityHeaders(next http.Handler) http.Handler
- func SetTimeout(timeout int) func(http.Handler) http.Handler
- func StartSession(store session.Store) func(http.Handler) http.Handler
- func SubstituteBindings(next http.Handler) http.Handler
- func Throttle(maxAttempts, decayMinutes int) func(http.Handler) http.Handler
- func ThrottleNamed(name string, maxAttempts, decayMinutes int) func(http.Handler) http.Handler
- func ThrottleRequests(limiter *cache.RateLimiter, maxAttempts int, decayMinutes int, name ...string) func(http.Handler) http.Handler
- func TrimAndConvertEmptyToNull(next http.Handler) http.Handler
- func TrimStrings(next http.Handler) http.Handler
- func TrustHostsMiddleware(trustedHosts ...string) func(http.Handler) http.Handler
- func TrustProxies(proxies []string) func(http.Handler) http.Handler
- func ValidatePostSize(maxSize int64) func(http.Handler) http.Handler
- func ValidateSignature(generator *routing.URLGenerator) func(http.Handler) http.Handler
- func VerifyCsrfToken(opts ...CsrfOptions) func(http.Handler) http.Handler
- type CorsConfig
- type CsrfOptions
- type MonitorConfig
- type RateLimiter
- type TrustedProxies
Constants ¶
const SessionKey = contextKey("session")
Variables ¶
This section is empty.
Functions ¶
func AddHeaders ¶
AddHeaders adds custom headers to the response
func AddRequestId ¶
AddRequestId adds a request ID to the response.
func Authenticate ¶
Authenticate returns a middleware that checks if the user is authenticated via the specified guard.
func AuthenticateSanctum ¶
AuthenticateSanctum authenticates Sanctum tokens.
func Authorize ¶
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 ¶
CacheFor sets Cache-Control with a max-age directive. Usage: CacheFor(3600) caches for 1 hour.
func CachePrivate ¶
CachePrivate sets Cache-Control to private with a max-age.
func CheckForMaintenanceMode ¶
CheckForMaintenanceMode middleware returns a 503 Service Unavailable if the app is down.
func ConfirmPassword ¶
ConfirmPassword requires password confirmation.
func ConvertEmptyStringsToNull ¶
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 ¶
CsrfTokenFromContext retrieves the CSRF token from the request context.
func EncryptCookies ¶
EncryptCookies middleware automatically decrypts incoming cookies and provides a hook (or relies on the cookie manager) for outgoing cookies.
func ErrorHandler ¶
ErrorHandler recovers from panics and converts them to HTTP responses. It handles HttpException natively, and converts other panics into 500s.
func GetSession ¶
GetSession is a helper to extract the session from the request context.
func LogRequests ¶
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 ¶
PermissionMiddleware checks if the user has a specific permission.
func PreloadLinks ¶
PreloadLinks sends Link headers for preloading resources
func PreventBackslash ¶
PreventBackslash prevents URLs with trailing slashes from being redirected
func PreventCache ¶
PreventCache is a convenience middleware that sets headers to prevent caching.
func PreventHTTPOnly ¶
PreventHTTPOnly ensures cookies are not accessible via JavaScript
func PreventHostHeaderAttack ¶
PreventHostHeaderAttack prevents host header attacks
func PreventLazyLoading ¶
PreventLazyLoading prevents lazy loading of resources
func PreventRequestsDuringMaintenance ¶
PreventRequestsDuringMaintenance returns middleware that prevents requests during maintenance mode
func Recovery ¶
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 ¶
RoleMiddleware checks if the authenticated user has the required role.
func SecurityHeaders ¶
SecurityHeaders injects standard secure HTTP headers into the response.
func SetCacheHeaders ¶
SetCacheHeaders sets HTTP cache control headers on the response. Usage: SetCacheHeaders("private, max-age=3600") or SetCacheHeaders("no-store, no-cache")
func SetCacheHeadersWithMap ¶
SetCacheHeadersWithMap sets HTTP cache control headers from a map. Usage: SetCacheHeadersWithMap(map[string]string{"Cache-Control": "max-age=3600", "ETag": "\"abc123\""})
func SetMiddlewareHeaders ¶
SetMiddlewareHeaders sets common middleware headers.
func SetSecurityHeaders ¶
SetSecurityHeaders sets common security headers
func SetTimeout ¶
SetTimeout sets a timeout for the request
func StartSession ¶
StartSession initializes the session for the request.
func SubstituteBindings ¶
SubstituteBindings substitutes route bindings.
func Throttle ¶
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 ¶
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 ¶
TrimAndConvertEmptyToNull combines TrimStrings and ConvertEmptyStringsToNull. This is the typical middleware stack used in Laravel's web middleware group.
func TrimStrings ¶
TrimStrings middleware trims whitespace from incoming string parameters. Handles URL query parameters, x-www-form-urlencoded, and multipart/form-data bodies.
func TrustHostsMiddleware ¶
TrustHostsMiddleware validates that the request Host header matches trusted hosts. If no trusted hosts are configured, all hosts are allowed.
func TrustProxies ¶
TrustProxies trusts proxy headers.
func ValidatePostSize ¶
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 ¶
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
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.