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.AccessLog()) // default config
app.GlobalMiddleware(middleware.AccessLog(middleware.AccessLogConfig{...})) // custom config
Built-in vs Configurable ¶
Credo provides built-in versions of Recover, RequestID, and AccessLog that are auto-enabled with zero configuration. Use the middleware package equivalents when you need custom configuration (e.g., custom header, skipper, custom logger). Disable the built-in first to avoid duplicates:
app, _ := credo.New(
credo.WithoutRequestID(), // disable built-in
credo.WithoutAccessLog(), // disable built-in
)
app.GlobalMiddleware(
middleware.RequestID(middleware.RequestIDConfig{Header: "X-Trace-Id"}),
middleware.AccessLog(middleware.AccessLogConfig{Skipper: mySkipper}),
)
Most configurable middleware in this package expose a Skipper for selective application. RequestID and Recover intentionally do not: RequestID is expected to run on every request, and Recover is intended to remain the outermost safety net.
Handlers can read the current request ID via ctx.RequestID() or GetRequestID.
Recommended Middleware Order ¶
Built-in middleware (recover, requestID, access log) runs automatically. Add extra global middleware for additional 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.
Additional middleware in this package:
- Rewrite(rules ...RewriteRule) — pre-dispatch URL path rewriting
- CORS(cfg ...CORSConfig)
- CSRF(cfg ...CSRFConfig) — Sec-Fetch-Site based, no tokens
- Secure(cfg ...SecureConfig)
- Compress(cfg ...CompressConfig)
- 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)
Index ¶
- Constants
- func AccessLog(cfg ...AccessLogConfig) credo.Middleware
- func CORS(cfg ...CORSConfig) credo.Middleware
- func CSRF(cfg ...CSRFConfig) credo.Middleware
- func Compress(cfg ...CompressConfig) credo.Middleware
- func ContractGuard(cfg ...ContractConfig) credo.Middleware
- func DefaultSkipper(*credo.Context) bool
- func GetRequestID(ctx *credo.Context) string
- func RateLimit(cfg ...RateLimitConfig) credo.Middleware
- func Recover(cfg ...RecoverConfig) credo.Middleware
- func RequestID(cfg ...RequestIDConfig) credo.Middleware
- func Rewrite(rules ...RewriteRule) credo.Middleware
- func RewriteWithConfig(cfg RewriteConfig) credo.Middleware
- func Secure(cfg ...SecureConfig) credo.Middleware
- func Timeout(cfg ...TimeoutConfig) credo.Middleware
- type AccessLogConfig
- type CORSConfig
- type CSRFConfig
- type CompressConfig
- type ContractConfig
- type RateLimitConfig
- type RateLimiter
- type RecoverConfig
- type RequestIDConfig
- 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 pass (there is no body to police). 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)
const RequestIDKey = internalrequestid.Key
RequestIDKey is the key used to store the request ID in the credo.Context request-scoped store. Exported for advanced integrations. Prefer credo.Context.RequestID or GetRequestID for normal request access.
Variables ¶
This section is empty.
Functions ¶
func AccessLog ¶
func AccessLog(cfg ...AccessLogConfig) credo.Middleware
AccessLog returns middleware that logs each HTTP request using slog with structured attributes: method, path, status, bytes, duration, remote_addr (from Request.RealIP), user_agent, request_id (if RequestID middleware is active), and path_original when the final served path differs from the client path.
Requests can be excluded two ways: the AccessLogConfig.Skipper predicate (consulted before the handler runs) and the credo.MetaAccessLog route meta set to false (consulted after the handler, once the route is known), which also silences a whole group via LookupMeta inheritance.
The log level varies by response status code:
- 2xx, 3xx: slog.LevelInfo
- 4xx: slog.LevelWarn
- 5xx: slog.LevelError
Example ¶
package main
import (
"io"
"log/slog"
"net/http"
"github.com/credo-go/credo"
"github.com/credo-go/credo/middleware"
)
func main() {
app, err := credo.New(credo.WithoutAccessLog())
if err != nil {
panic(err)
}
app.GlobalMiddleware(middleware.AccessLog(middleware.AccessLogConfig{
Logger: slog.New(slog.NewJSONHandler(io.Discard, nil)),
}))
app.GET("/", func(ctx *credo.Context) error {
return ctx.Response().Text(http.StatusOK, "ok")
})
}
Output:
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, and OPTIONS — safe methods are always allowed; never perform state changes in them.
- 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: 403 Problem Details 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 Compress ¶
func Compress(cfg ...CompressConfig) credo.Middleware
Compress returns response compression middleware.
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 GetRequestID ¶
GetRequestID returns the request ID from the Credo context. It returns an empty string if no request ID has been set.
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 Recover ¶
func Recover(cfg ...RecoverConfig) credo.Middleware
Recover returns middleware that recovers from panics, logs the panic using slog, and returns an HTTP 500 Internal Server Error response.
Note: Credo includes built-in panic recovery by default (see credo.WithoutRecover). This middleware is useful when you need per-group/per-route recovery with custom configuration (e.g., custom logger, stack size control, or disabled stack traces).
The http.ErrAbortHandler sentinel is re-panicked to allow the HTTP server to abort the connection as intended.
func RequestID ¶
func RequestID(cfg ...RequestIDConfig) credo.Middleware
RequestID returns middleware that injects a unique request ID into each request's context and response headers. If the incoming request already has an X-Request-Id header (within the configured length limit), that value is used. Otherwise, a new ID is generated.
Like the built-in request ID tier, it also enriches the request-scoped logger with a "request_id" attribute (via credo.Context.AddLogAttrs), so handler logs and the access log carry the ID automatically.
The request ID can be retrieved in downstream handlers via credo.Context.RequestID or GetRequestID.
Example (CustomHeader) ¶
package main
import (
"net/http"
"github.com/credo-go/credo"
"github.com/credo-go/credo/middleware"
)
func main() {
app, err := credo.New(credo.WithoutRequestID(), credo.WithoutAccessLog())
if err != nil {
panic(err)
}
app.GET("/", func(ctx *credo.Context) error {
traceID := middleware.GetRequestID(ctx)
_ = traceID
return ctx.Response().NoContent(http.StatusOK)
}).Middleware(middleware.RequestID(middleware.RequestIDConfig{
Header: "X-Trace-Id",
}))
}
Output:
func Rewrite ¶
func Rewrite(rules ...RewriteRule) 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 is the rule-list shortcut; use RewriteWithConfig to set a Skipper alongside the rules.
Panics if rules is empty.
func RewriteWithConfig ¶
func RewriteWithConfig(cfg RewriteConfig) credo.Middleware
RewriteWithConfig is the config-struct variant of Rewrite.
Panics if cfg.Rules is empty.
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 AccessLogConfig ¶
type AccessLogConfig struct {
// Logger is used to log request information.
// Default: ctx.Logger() (the request-scoped logger from the app).
Logger *slog.Logger
// Skipper defines a function to skip logging for certain requests.
// When Skipper returns true, the request is not logged.
// Useful for health check endpoints or static assets.
// Default: DefaultSkipper (all requests are logged).
Skipper Skipper
}
AccessLogConfig defines configuration for the AccessLog middleware.
func DefaultAccessLogConfig ¶
func DefaultAccessLogConfig() AccessLogConfig
DefaultAccessLogConfig returns the default AccessLog middleware config. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
type CORSConfig ¶
type CORSConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// AllowOrigins defines allowed origins.
// 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.
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 CompressConfig ¶
type CompressConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Level is the gzip/deflate compression level (1–9). The zero value
// selects the default (5); level 0 (NoCompression) cannot be requested
// through this middleware — omit the middleware or use Skipper to skip
// compression entirely.
Level int
// Types limits compression to specific content types.
// Supports exact values ("application/json") and wildcards ("text/*").
// Default: common textual MIME types.
Types []string
}
CompressConfig defines configuration for Compress middleware.
func DefaultCompressConfig ¶
func DefaultCompressConfig() CompressConfig
DefaultCompressConfig returns the default Compress 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
// 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 RecoverConfig ¶
type RecoverConfig struct {
// Logger is used to log panic information.
// Default: ctx.Logger() (the request-scoped logger from the app).
Logger *slog.Logger
// DisableStackTrace disables stack trace logging on panic.
// Default: false (stack traces are enabled).
DisableStackTrace bool
// StackSize is the maximum number of bytes for the stack trace.
// Default: 8192.
StackSize int
}
RecoverConfig defines configuration for the Recover middleware.
func DefaultRecoverConfig ¶
func DefaultRecoverConfig() RecoverConfig
DefaultRecoverConfig returns the default Recover middleware config. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
type RequestIDConfig ¶
type RequestIDConfig struct {
// Header is the HTTP header name used to read/write the request ID.
// Default: "X-Request-Id".
Header string
// Generator creates a new request ID when one is not provided by the
// client. Default: crypto/rand.Text (128-bit base32 string).
Generator func() string
// Limit is the maximum allowed length for incoming request IDs. IDs
// exceeding this length are discarded and a new one is generated.
// This prevents clients from injecting arbitrarily large values.
// Default: 64.
Limit int
}
RequestIDConfig defines configuration for the RequestID middleware.
func DefaultRequestIDConfig ¶
func DefaultRequestIDConfig() RequestIDConfig
DefaultRequestIDConfig returns the default RequestID middleware config. Each call returns a fresh value, so callers cannot mutate the package-wide defaults.
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.
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.