Documentation
¶
Overview ¶
Package middleware provides built-in HTTP middleware for the Credo framework.
All middleware in this package returns credo.Middleware, the single middleware type used throughout Credo:
func(credo.Handler) credo.Handler
Stdlib-compatible middleware (func(http.Handler) http.Handler) can be adapted using credo.WrapStdMiddleware.
Config Struct Pattern ¶
Middleware with options uses an optional config parameter:
app.GlobalMiddleware(middleware.CORS()) // default config
app.GlobalMiddleware(middleware.CORS(middleware.CORSConfig{...})) // custom config
Framework Features Are Not Middleware ¶
Panic recovery, request IDs, access logging, response compression, request decompression and locale detection are framework-owned HTTP features of the root package, not middleware: recovery is on by default (configure it with credo.WithRecoverConfig, disable it with credo.WithoutRecover) and the others are installed once per App through credo.App.UseRequestID, credo.App.UseAccessLog, credo.App.UseCompress, credo.App.UseDecompress and credo.App.UseI18n. The request executor runs them in a fixed order around the whole user chain, so they observe the final response — error envelopes and panic responses included — and cannot be applied per route or per group. Handlers read the current request ID via ctx.RequestID().
Most middleware in this package expose a Skipper for selective application.
Recommended Middleware Order ¶
Add global middleware for cross-cutting concerns:
app.GlobalMiddleware(
middleware.Secure(), // Security headers
middleware.CORS(), // CORS headers
)
Global middleware runs on every request, including 404 and 405 responses. Group middleware (group.Middleware) only runs on matched routes in that group. Group middleware is captured at route registration time: calling group.Middleware(...) affects routes registered after that call, not previously registered routes.
Middleware in this package:
- Rewrite(cfg ...RewriteConfig) — pre-dispatch URL path rewriting
- CORS(cfg ...CORSConfig)
- CSRF(cfg ...CSRFConfig) — Sec-Fetch-Site based, no tokens
- Secure(cfg ...SecureConfig)
- Timeout(cfg ...TimeoutConfig)
- RateLimit(cfg ...RateLimitConfig)
RateLimit Lifecycle ¶
For explicit lifecycle control, use NewRateLimiter and register limiter.Shutdown with app.OnShutdown:
ratelimiter := middleware.NewRateLimiter(middleware.RateLimitConfig{Tokens: 120})
app.GlobalMiddleware(ratelimiter.Middleware())
app.OnShutdown(ratelimiter.Shutdown)
Maturity: beta
Index ¶
- Constants
- func CORS(cfg ...CORSConfig) credo.Middleware
- func CSRF(cfg ...CSRFConfig) credo.Middleware
- func ContractGuard(cfg ...ContractConfig) credo.Middleware
- func DefaultSkipper(*credo.Context) bool
- func RateLimit(cfg ...RateLimitConfig) credo.Middleware
- func Rewrite(cfg ...RewriteConfig) credo.Middleware
- func Secure(cfg ...SecureConfig) credo.Middleware
- func Timeout(cfg ...TimeoutConfig) credo.Middleware
- type CORSConfig
- type CSRFConfig
- type ContractConfig
- type RateLimitConfig
- type RateLimiter
- type RewriteConfig
- type RewriteRule
- type SecureConfig
- type Skipper
- type TimeoutConfig
Examples ¶
Constants ¶
const ( // MetaAccept restricts the request Content-Type to the listed media types. // Values may use a "type/*" or "*/*" wildcard. Requests without a // Content-Type header (or with an empty one) pass by default; set // ContractConfig.RequireContentType to reject them with 415 when the // request carries a body. MetaAccept = "accept" // MetaMaxBody caps the request body size in bytes for the route. It is // enforced both eagerly (Content-Length) and while streaming (a tighter // http.MaxBytesReader layered on the global server limit — defense in // depth). A negative value disables the per-route cap. MetaMaxBody = "max_body" // MetaRequireHeaders lists request headers that must be present and // non-empty. MetaRequireHeaders = "require_headers" // MetaRequireQuery lists query parameters that must be present and // non-empty. MetaRequireQuery = "require_query" // MetaAPIVersion lists the acceptable API versions. The request version is // read from the configured header (default "X-API-Version"), falling back // to a "version" route parameter (e.g. /v{version}/...). MetaAPIVersion = "api_version" // MetaScope lists scopes the request must satisfy (all of them). It is // evaluated by ContractConfig.ScopeChecker; if no checker is configured, // a route declaring this contract is denied (a declared scope is never // silently bypassed). This shares the "scope" meta key documented for the // auth package. MetaScope = "scope" )
Contract meta keys. Set them on a route or group with SetMeta; ContractGuard reads them — with parent-chain inheritance via credo.Route.LookupMeta — and enforces the matching request contract before the handler runs:
api := app.Group("/api")
api.SetMeta(middleware.MetaAccept, "application/json") // group-wide
api.POST("/users", createUser).
SetMeta(middleware.MetaMaxBody, int64(1<<20)). // 1 MiB
SetMeta(middleware.MetaRequireHeaders, []string{"X-Request-Id"})
Accepted value types:
MetaAccept string | []string -> 415 Unsupported Media Type MetaMaxBody int | int32 | int64 (bytes) -> 413 Payload Too Large MetaRequireHeaders string | []string -> 400 Bad Request MetaRequireQuery string | []string -> 400 Bad Request MetaAPIVersion string | []string -> 400 Bad Request MetaScope string | []string -> 403 Forbidden (needs ScopeChecker)
The types are matched exactly; a []any whose elements are all strings is read like a []string. A declared contract is never skipped: when the guard reaches a value of any other type — a named string type (type Scope string), a nil, a []any holding a non-string element — it rejects the request with the generic 500 instead of calling the handler, and the server-error log names the route, the key, the value's Go type and the fix. Convert named types where the contract is declared:
api.GET("/reports", listReports).SetMeta(middleware.MetaScope, string(ScopeReports))
A route overrides a contract inherited from its group by setting the key itself. To lift an inherited requirement, set the value that requires nothing: an empty list ([]string{}) for MetaRequireHeaders, MetaRequireQuery and MetaScope, "*/*" for MetaAccept (every media type; ContractConfig.RequireContentType still applies), a negative value for MetaMaxBody. An empty MetaAPIVersion list accepts no version, so that contract can be replaced but not lifted.
Variables ¶
This section is empty.
Functions ¶
func CSRF ¶
func CSRF(cfg ...CSRFConfig) credo.Middleware
CSRF returns middleware that rejects non-safe cross-origin browser requests, protecting state-changing endpoints against Cross-Site Request Forgery. It wraps the standard library's http.CrossOriginProtection, which detects cross-origin requests via the Sec-Fetch-Site header — sent by all modern browsers — with an Origin/Host comparison fallback for older ones. No tokens, cookies, or session state are involved, so there is no per-request overhead beyond a header check.
What passes, in detector order:
- GET, HEAD, OPTIONS, and QUERY — safe methods are always allowed; never perform state changes in them. QUERY is handled explicitly because Go 1.27's CrossOriginProtection predates RFC 10008.
- Sec-Fetch-Site: same-origin or none — same-origin browser requests.
- Requests with neither Sec-Fetch-Site nor Origin headers — non-browser clients (curl, server-to-server, mobile SDKs) are unaffected.
- Origin matching the Host header (older browsers without Sec-Fetch-Site).
- Origins listed in CSRFConfig.TrustedOrigins and paths matching CSRFConfig.InsecureBypassPatterns.
Everything else — in particular Sec-Fetch-Site: cross-site and same-site (subdomains!) — is rejected through CSRFConfig.ErrorHandler (default: centralized 403 error response via the framework error pipeline; the stdlib deny handler is not used).
CSRF and CORS are complementary, not interchangeable: CORS governs whether a browser may *read* a cross-origin response, while CSRF protection stops state-changing cross-origin requests from being *processed*. APIs serving browser frontends on other origins typically need both, with the frontend origins in both allow lists.
Register it globally or per group:
app.GlobalMiddleware(middleware.CSRF())
app.GlobalMiddleware(middleware.CSRF(middleware.CSRFConfig{
TrustedOrigins: []string{"https://app.example.com"},
InsecureBypassPatterns: []string{"/webhooks/"},
}))
Panics if a TrustedOrigins entry is not a valid "scheme://host[:port]" origin, or if an InsecureBypassPatterns entry is syntactically invalid or conflicts with another — middleware construction is startup configuration (see the credo package's "Panics and Errors" section).
func ContractGuard ¶
func ContractGuard(cfg ...ContractConfig) credo.Middleware
ContractGuard returns a single middleware that enforces declarative, meta-driven request contracts. Routes (or groups) opt in by setting the Meta* keys; routes without any contract meta pass through untouched.
Register it at the group (or route) level, not via App.GlobalMiddleware: the guard reads matched-route metadata, and a route is only matched after app-global middleware has run. Group and route middleware run after the match, so the route — and its inherited group meta — is available there.
api := app.Group("/api")
api.Middleware(middleware.ContractGuard())
api.POST("/users", createUser).
SetMeta(middleware.MetaAccept, "application/json").
SetMeta(middleware.MetaMaxBody, int64(1<<20))
Applied globally the guard is a safe no-op (it skips when no route is matched) rather than an error. Each contract maps a route Meta key to an HTTP rejection: see the Meta* constants for the value types and status codes.
func DefaultSkipper ¶
DefaultSkipper never skips middleware.
func RateLimit ¶
func RateLimit(cfg ...RateLimitConfig) credo.Middleware
RateLimit returns rate-limiting middleware.
This convenience constructor owns its default in-memory store for the lifetime of the middleware. That store runs no background goroutines — expired buckets are swept inline during Take — so there is nothing that must be stopped at shutdown; closing it would only release memory early. For deterministic store release (short-lived middleware, tests) or a custom store lifecycle, use NewRateLimiter and register RateLimiter.Shutdown with app.OnShutdown.
func Rewrite ¶
func Rewrite(cfg ...RewriteConfig) credo.Middleware
Rewrite returns middleware that rewrites URL paths before dispatch. Rules are evaluated in order; the first match wins. The rewrite is transparent to the client (no redirect).
Rewrite follows the package-wide config-struct convention: pass one RewriteConfig carrying the Rules and an optional Skipper.
middleware.Rewrite(middleware.RewriteConfig{
Rules: []middleware.RewriteRule{
{From: "/v1/{path...}", To: "/api/v1/{path}"},
},
})
Panics if cfg.Rules is empty or a From pattern is malformed.
func Secure ¶
func Secure(cfg ...SecureConfig) credo.Middleware
Secure returns middleware that sets common security headers.
func Timeout ¶
func Timeout(cfg ...TimeoutConfig) credo.Middleware
Timeout returns request timeout middleware.
It replaces the request context with one carrying the configured deadline; handlers and downstream calls observe it via ctx.Context(). When the chain returns context.DeadlineExceeded, the default ErrorHandler maps it to 503 with the request-timeout message key.
Enforcement is cooperative. Unlike http.TimeoutHandler, this middleware does not buffer the response or cut off writes once the deadline passes — a handler that ignores its context can keep writing to the client. Pass ctx.Context() to blocking work (database queries, outbound requests) so it actually aborts on deadline.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// AllowOrigins defines allowed origins. Each entry is either "*" (allow
// every origin) or an origin in the strict scheme://host[:port] grammar
// shared with the websocket adapter's AllowedOrigins: http or https only;
// no path, query, fragment, or userinfo; scheme and host compare
// case-insensitively; the scheme's default port is implied. One wildcard
// may stand for exactly the left-most DNS label: "https://*.example.com"
// matches "https://app.example.com" but not "https://example.com" or
// "https://a.b.example.com". Any other shape (mid-label "*", several
// wildcards, IP wildcards, empty entries) panics at construction.
// Default: ["*"].
AllowOrigins []string
// AllowOriginFunc overrides AllowOrigins matching.
AllowOriginFunc func(ctx *credo.Context, origin string) (allowedOrigin string, allowed bool, err error)
// AllowMethods defines allowed methods for preflight.
// Default: GET, HEAD, PUT, PATCH, POST, DELETE, QUERY.
AllowMethods []string
// AllowHeaders defines allowed request headers for preflight.
// If empty, Access-Control-Request-Headers is echoed.
AllowHeaders []string
// AllowCredentials enables Access-Control-Allow-Credentials.
AllowCredentials bool
// ExposeHeaders defines exposed response headers.
ExposeHeaders []string
// MaxAge sets Access-Control-Max-Age in seconds.
// Zero disables this header.
MaxAge int
}
CORSConfig defines configuration for CORS middleware.
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig returns the default CORS middleware config. Each call returns a fresh value (including fresh slices), so callers cannot mutate the package-wide defaults.
type CSRFConfig ¶
type CSRFConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// TrustedOrigins lists origins whose cross-origin requests are allowed.
// Each entry must be of the form "scheme://host[:port]" and is matched
// exactly against the request's Origin header.
//
// Subdomains are cross-origin: a form on app.example.com posting to
// api.example.com is rejected unless "https://app.example.com" is listed
// here (browsers send Sec-Fetch-Site: same-site for that case, which is
// not trusted by default).
TrustedOrigins []string
// InsecureBypassPatterns lists path patterns exempt from cross-origin
// checks, using [http.ServeMux] pattern syntax (e.g. "/webhooks/",
// "POST /payments/callback"). Matching requests skip CSRF protection
// entirely — reserve this for endpoints that authenticate by other
// means (signed webhooks, mTLS) and keep the list as narrow as possible.
InsecureBypassPatterns []string
// ErrorHandler maps a rejected request to the error returned by the
// middleware. The rejection reason from the detector is passed as err.
// Default: 403 *credo.HTTPError with the reason attached as internal
// error (logged, never exposed to the client).
ErrorHandler func(ctx *credo.Context, err error) error
}
CSRFConfig defines configuration for the CSRF middleware.
func DefaultCSRFConfig ¶
func DefaultCSRFConfig() CSRFConfig
DefaultCSRFConfig returns the default CSRF middleware config. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
type ContractConfig ¶
type ContractConfig struct {
// Skipper defines a function to skip the middleware for a request.
Skipper Skipper
// ScopeChecker enforces the MetaScope contract. It receives the request
// context and a single required scope and reports whether the request
// satisfies it. Because authenticated users are stored generically
// (ctx.GetUser[T]), the framework cannot inspect scopes on its own —
// supply this to bridge to your auth model. When nil, any route that
// declares a scope contract is rejected with 403.
ScopeChecker func(ctx *credo.Context, requiredScope string) bool
// APIVersionHeader is the request header inspected for the MetaAPIVersion
// contract. Defaults to "X-API-Version".
APIVersionHeader string
// RequireContentType arms the MetaAccept contract against requests that
// carry a body but no (or an empty) Content-Type header: such requests
// are rejected with 415 instead of passing. A body is assumed when
// Content-Length is positive or unknown (chunked, HTTP/2 streams);
// requests with Content-Length 0 and bodiless requests pass, and routes
// without a MetaAccept contract are unaffected. Default false.
RequireContentType bool
// CustomChecks run after all built-in contracts have passed, in order.
// A check returns a non-nil error (typically a *credo.HTTPError) to reject
// the request. This is the extension point for user-defined contracts.
CustomChecks []func(ctx *credo.Context) error
}
ContractConfig configures the ContractGuard middleware.
func DefaultContractConfig ¶
func DefaultContractConfig() ContractConfig
DefaultContractConfig returns the default ContractGuard configuration. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
type RateLimitConfig ¶
type RateLimitConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Store is the backing limiter store.
// Default: in-memory store with Tokens/Interval.
Store limiter.Store
// Tokens is the number of allowed requests per interval.
// Default: 60.
Tokens uint64
// Interval is the refill interval.
// Default: 1 minute.
Interval time.Duration
// KeyFunc builds a limiter key from the request context.
// Default: client IP from ctx.Request().RealIP().
KeyFunc func(ctx *credo.Context) (string, error)
// InternalErrorHandler handles internal limiter/key errors (key
// extraction failure, store failure). Over-limit responses go through
// DeniedHandler instead.
InternalErrorHandler func(ctx *credo.Context, err error) error
// DeniedHandler handles over-limit responses.
DeniedHandler func(ctx *credo.Context, limit, remaining uint64, reset time.Time) error
}
RateLimitConfig defines configuration for RateLimit middleware.
func DefaultRateLimitConfig ¶
func DefaultRateLimitConfig() RateLimitConfig
DefaultRateLimitConfig returns the default RateLimit middleware config. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter builds middleware from a normalized config and optionally owns the lifecycle of its internally created store.
func NewRateLimiter ¶
func NewRateLimiter(cfg RateLimitConfig) *RateLimiter
NewRateLimiter creates a reusable rate limiter instance.
If cfg.Store is nil, NewRateLimiter creates an internal in-memory store and owns its lifecycle. Call Close/Shutdown during app shutdown to release resources when using this constructor directly.
Example ¶
package main
import (
"github.com/credo-go/credo"
"github.com/credo-go/credo/middleware"
)
func main() {
app, err := credo.New()
if err != nil {
panic(err)
}
limiter := middleware.NewRateLimiter(middleware.RateLimitConfig{Tokens: 120})
app.GlobalMiddleware(limiter.Middleware())
app.OnShutdown(limiter.Shutdown)
}
Output:
func (*RateLimiter) Close ¶
func (r *RateLimiter) Close(ctx context.Context) error
Close closes the internally created store if this limiter owns it.
Custom stores passed via RateLimitConfig.Store are not closed automatically.
func (*RateLimiter) Middleware ¶
func (r *RateLimiter) Middleware() credo.Middleware
Middleware returns Credo middleware for this RateLimiter.
type RewriteConfig ¶
type RewriteConfig struct {
// Skipper skips rewriting for matching requests.
Skipper Skipper
// Rules are evaluated in order; the first match wins.
Rules []RewriteRule
}
RewriteConfig defines configuration for the Rewrite middleware.
func DefaultRewriteConfig ¶ added in v0.16.0
func DefaultRewriteConfig() RewriteConfig
DefaultRewriteConfig returns the default Rewrite middleware config: no Skipper and no rules (a rule list is required). Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
type RewriteRule ¶
type RewriteRule struct {
// Host restricts the rule to requests matching this exact host (case-insensitive).
// Empty matches all hosts.
Host string
// From is the path pattern to match. Supports Credo route syntax:
// - {name} — matches a single path segment
// - {name...} — matches the rest of the path
// - {name:regex} — matches with regex constraint
// Ignored when Regexp is set.
From string
// To is the replacement path. Named placeholders ({name}) are expanded
// with captured values.
To string
// Regexp is an optional pre-compiled regex. When set, From is ignored.
// Named capture groups (?P<name>...) are used for placeholder expansion.
Regexp *regexp.Regexp
// PreserveQuery appends the original query string to the rewritten URL
// when To does not contain a query string.
PreserveQuery bool
}
RewriteRule defines a URL rewrite rule for the Rewrite middleware.
type SecureConfig ¶
type SecureConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// XSSProtection sets the X-XSS-Protection header value.
XSSProtection string
// ContentTypeNosniff sets the X-Content-Type-Options header value.
ContentTypeNosniff string
// XFrameOptions sets the X-Frame-Options header value.
XFrameOptions string
// HSTSMaxAge sets Strict-Transport-Security max-age in seconds.
HSTSMaxAge int
// HSTSExcludeSubdomains disables includeSubDomains in HSTS.
HSTSExcludeSubdomains bool
// HSTSPreloadEnabled adds preload token in HSTS.
HSTSPreloadEnabled bool
// ContentSecurityPolicy sets CSP or CSP-Report-Only header value.
ContentSecurityPolicy string
// CSPReportOnly uses Content-Security-Policy-Report-Only header.
CSPReportOnly bool
// ReferrerPolicy sets the Referrer-Policy header value.
ReferrerPolicy string
}
SecureConfig defines configuration for Secure middleware.
func DefaultSecureConfig ¶
func DefaultSecureConfig() SecureConfig
DefaultSecureConfig returns the default Secure middleware config. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
type TimeoutConfig ¶
type TimeoutConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Timeout defines request context timeout.
// Zero or negative values disable timeout behavior.
Timeout time.Duration
// ErrorHandler maps downstream errors after timeout wrapping.
ErrorHandler func(ctx *credo.Context, err error) error
}
TimeoutConfig defines configuration for Timeout middleware.
func DefaultTimeoutConfig ¶
func DefaultTimeoutConfig() TimeoutConfig
DefaultTimeoutConfig returns the default Timeout middleware config. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.