Documentation
¶
Index ¶
- func CORS(config ...CORSConfig) kruda.HandlerFunc
- func CSRF(config ...CSRFConfig) kruda.HandlerFunc
- func Logger(config ...LoggerConfig) kruda.HandlerFunc
- func PathTraversal() kruda.HandlerFunc
- func Recovery(config ...RecoveryConfig) kruda.HandlerFunc
- func RequestID(config ...RequestIDConfig) kruda.HandlerFunc
- func Timeout(duration time.Duration) kruda.HandlerFunc
- type CORSConfig
- type CSRFConfig
- type LoggerConfig
- type RecoveryConfig
- type RequestIDConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CORS ¶
func CORS(config ...CORSConfig) kruda.HandlerFunc
CORS returns middleware that handles Cross-Origin Resource Sharing. It supports both preflight (OPTIONS) and non-preflight requests. Panics if AllowCredentials is true with AllowOrigins=["*"] per CORS spec. Adds Vary: Origin header when origin is not wildcard. Expose-Headers is only set on non-preflight responses.
func CSRF ¶
func CSRF(config ...CSRFConfig) kruda.HandlerFunc
CSRF returns middleware that provides Cross-Site Request Forgery protection using the double-submit cookie pattern.
For safe methods (GET, HEAD, OPTIONS, TRACE), it generates a new token, sets it as a cookie, and stores it in the request context via c.Set("csrf_token", token).
For unsafe methods (POST, PUT, DELETE, PATCH), it validates the token from the X-CSRF-Token header (or custom header) against the cookie value using constant-time comparison.
Usage:
app.Use(middleware.CSRF())
// In handler — get token for template rendering:
token := c.Get("csrf_token").(string)
func Logger ¶
func Logger(config ...LoggerConfig) kruda.HandlerFunc
Logger returns middleware that logs request information using slog. It logs method, path, status code, latency, and client IP. Log level is determined by status code: 5xx=Error, 4xx=Warn, 2xx/3xx=Info. Status is resolved from the error if the handler returned one, since handleError hasn't set the status on Ctx yet when Logger reads it.
func PathTraversal ¶
func PathTraversal() kruda.HandlerFunc
PathTraversal returns middleware that prevents path traversal attacks. It decodes percent-encoded sequences, then checks for ".." segments that would escape above the root directory. Such requests are rejected with a 400 Bad Request error.
Usage:
app.Use(middleware.PathTraversal())
func Recovery ¶
func Recovery(config ...RecoveryConfig) kruda.HandlerFunc
Recovery returns middleware that recovers from panics in handlers, logs the panic value and stack trace, and returns a 500 Internal Server Error. Returns an InternalError so that OnError hooks fire properly. It accepts an optional RecoveryConfig for customization.
func RequestID ¶
func RequestID(config ...RequestIDConfig) kruda.HandlerFunc
RequestID returns middleware that ensures every request has a unique ID. If the incoming request already has an X-Request-ID header, it uses that value after validation (length check, printable ASCII only). Otherwise, it generates a UUID v4 using crypto/rand. The request ID is stored in the context via c.Set("request_id", id) and set as a response header.
func Timeout ¶
func Timeout(duration time.Duration) kruda.HandlerFunc
Timeout returns middleware that sets a deadline on the request context. If the handler's context-aware operations exceed the specified duration, they will receive a context.DeadlineExceeded error.
The handler runs synchronously (no goroutine) to avoid data races on Ctx, use-after-free from pool reuse, and goroutine leaks. The timeout is enforced via context cancellation — handlers should check c.Context().Done() or pass c.Context() to I/O operations.
If the handler returns and the context deadline has been exceeded, a 503 Service Unavailable response is returned.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// AllowOrigins is a list of origins that are allowed to make cross-origin requests.
// Default: ["*"]
AllowOrigins []string
// AllowMethods is a list of HTTP methods allowed for cross-origin requests.
// Default: ["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"]
AllowMethods []string
// AllowHeaders is a list of HTTP headers allowed in cross-origin requests.
// Default: ["Origin","Content-Type","Accept","Authorization"]
AllowHeaders []string
// AllowCredentials indicates whether the response to the request can be
// exposed when the credentials flag is true.
// Default: false
AllowCredentials bool
// ExposeHeaders is a list of headers that browsers are allowed to access.
// Default: []
ExposeHeaders []string
// MaxAge indicates how long (in seconds) the results of a preflight request
// can be cached.
// Default: 86400
MaxAge int
}
CORSConfig holds configuration for the CORS middleware.
type CSRFConfig ¶
type CSRFConfig struct {
// CookieName is the name of the cookie that stores the CSRF token.
// Default: "_csrf"
CookieName string
// HeaderName is the HTTP header to check for the CSRF token.
// Default: "X-CSRF-Token"
HeaderName string
// CookiePath sets the Path attribute of the CSRF cookie.
// Default: "/"
CookiePath string
// CookieDomain sets the Domain attribute of the CSRF cookie.
// Default: "" (current domain)
CookieDomain string
// CookieSecure sets the Secure flag on the CSRF cookie.
// Default: false
CookieSecure bool
// SameSite sets the SameSite attribute of the CSRF cookie.
// Default: http.SameSiteStrictMode
SameSite http.SameSite
// MaxAge is the cookie max-age in seconds.
// Default: 3600 (1 hour)
MaxAge int
// TokenLength is the number of random bytes in the token.
// The cookie value will be hex-encoded (2× this length).
// Default: 32 (64 hex characters)
TokenLength int
// Skip is an optional function to skip CSRF protection for certain requests.
// Return true to skip validation entirely.
Skip func(*kruda.Ctx) bool
// ErrorHandler is an optional custom error handler for CSRF failures.
// Default: 403 JSON response {"error": "csrf_token_invalid"}
ErrorHandler func(*kruda.Ctx) error
}
CSRFConfig holds configuration for the CSRF middleware.
type LoggerConfig ¶
type LoggerConfig struct {
// Logger is the slog.Logger to use for logging.
// Default: slog.Default()
Logger *slog.Logger
// SkipPaths is a list of paths to skip logging (e.g. "/health", "/metrics").
SkipPaths []string
}
LoggerConfig holds configuration for the Logger middleware.
type RecoveryConfig ¶
type RecoveryConfig struct {
// Logger is the slog.Logger for logging panics.
// Default: slog.Default()
Logger *slog.Logger
// PanicHandler is an optional custom handler called when a panic is recovered.
// If set, it replaces the default behavior (log + 500 response).
PanicHandler func(c *kruda.Ctx, v any)
// DisableStackTrace skips capturing and logging stack traces on panic.
// Enable in production to avoid leaking internal paths in logs.
// Default: false
DisableStackTrace bool
}
RecoveryConfig holds configuration for the Recovery middleware.
type RequestIDConfig ¶
type RequestIDConfig struct {
// Header is the HTTP header name used for the request ID.
// Default: "X-Request-ID"
Header string
// Generator is a function that returns a new unique ID.
// Default: UUID v4 via crypto/rand
Generator func() string
}
RequestIDConfig holds configuration for the RequestID middleware.