middleware

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.PreRouting(middleware.CORS())                            // default config
app.PreRouting(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 c.RequestID().

Most middleware in this package expose a Skipper for selective application.

The user tiers run PreRouting → routed → Group → Route. A middleware that acts before the match or on a request no route matches goes before routing; one that reads the matched route goes on the routed tier, which runs on every route of the App and never for the router's 404 and 405:

app.PreRouting(
    middleware.Secure(), // headers on the 404 and 405 too
    middleware.CORS(),   // answers a preflight no route serves
)
app.Middleware(middleware.ContractGuard()) // reads each route's meta

Rewrite (it changes the path that routing matches) and RateLimit stay before routing; CSRF works on either tier; authentication and ContractGuard go on the routed tier, a group or a route. Group middleware (group.Middleware) runs on the routes of that group. Routed and group middleware are collected when the routes' chains are compiled, so they apply to routes registered before the call too.

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)

Rate limiting is the package github.com/credo-go/credo/middleware/ratelimit (ratelimit.Middleware(cfg ...ratelimit.Config)), so that importing this package does not link go-limiter.

Maturity: beta

Example (MetaDrivenMiddleware)

Middleware reads route meta to decide per route; a route's own value overrides its group's.

package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/credo-go/credo"
)

func exampleApp() *credo.App {
	app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
	if err != nil {
		panic(err)
	}
	return app
}

func exampleServe(app *credo.App, req *http.Request) {
	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, req)
	fmt.Println(req.Method, req.URL.RequestURI(), "→", rec.Code, rec.Body.String())
}

var RequireAuth = credo.NewKey[bool]("auth")

func main() {
	validateToken := func(h string) bool { return h == "Bearer good" }
	Auth := func(next credo.Handler) credo.Handler {
		return func(c *credo.Context) error {
			if required, _ := c.Route().GetMeta(RequireAuth); required {
				if !validateToken(c.Request().Header.Get("Authorization")) {
					return credo.NewHTTPError(http.StatusUnauthorized)
				}
			}
			return next(c)
		}
	}
	ok := func(c *credo.Context) error { return c.Response().Text(http.StatusOK, "ok") }

	app := exampleApp()
	api := app.Group("/api")
	api.SetMeta(RequireAuth, true).Middleware(Auth)

	api.GET("/users", ok)                              // authenticated
	api.GET("/health", ok).SetMeta(RequireAuth, false) // not authenticated

	exampleServe(app, httptest.NewRequest(http.MethodGet, "/api/users", nil))
	exampleServe(app, httptest.NewRequest(http.MethodGet, "/api/health", nil))
}
Output:
GET /api/users → 401 {"success":false,"error":{"code":"unauthorized","message":"Unauthorized"}}
GET /api/health → 200 ok

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// 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 = credo.NewKey[[]string]("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 = credo.NewKey[int64]("max_body")

	// MetaRequireHeaders lists request headers that must be present and
	// non-empty.
	MetaRequireHeaders = credo.NewKey[[]string]("require_headers")

	// MetaRequireQuery lists query parameters that must be present and
	// non-empty.
	MetaRequireQuery = credo.NewKey[[]string]("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 = credo.NewKey[[]string]("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).
	MetaScope = credo.NewKey[[]string]("scope")
)

Contract meta keys. Set them on a route, a group or the App with SetMeta; ContractGuard reads them — the route's value, else its groups', else the App's, through credo.Route.GetMeta — and enforces the matching request contract before the handler runs. Each key's value type is checked at compile time:

api := app.Group("/api")
api.SetMeta(middleware.MetaAccept, []string{"application/json"}) // group-wide
api.POST("/users", createUser).
    SetMeta(middleware.MetaMaxBody, 1<<20). // 1 MiB
    SetMeta(middleware.MetaRequireHeaders, []string{"X-Request-Id"})

The rejections:

MetaAccept          -> 415 Unsupported Media Type
MetaMaxBody         -> 413 Payload Too Large
MetaRequireHeaders  -> 400 Bad Request
MetaRequireQuery    -> 400 Bad Request
MetaAPIVersion      -> 400 Bad Request
MetaScope           -> 403 Forbidden (needs ScopeChecker)

A route overrides a contract inherited from its group by setting the key itself, and lifts an inherited requirement with the value that requires nothing: an empty list for MetaRequireHeaders, MetaRequireQuery and MetaScope, []string{"*/*"} 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.

Functions

func CORS

func CORS(cfg ...CORSConfig) credo.Middleware

CORS returns CORS middleware.

Example

Each constructor takes an optional config: none selects the defaults, one customizes.

package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/credo-go/credo"
	"github.com/credo-go/credo/middleware"
)

func exampleApp() *credo.App {
	app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
	if err != nil {
		panic(err)
	}
	return app
}

func main() {
	app := exampleApp()
	app.PreRouting(middleware.CORS(middleware.CORSConfig{
		AllowOrigins: []string{"https://example.com"},
		AllowMethods: []string{"GET", "POST"},
	}))
	app.GET("/data", func(c *credo.Context) error { return c.Response().Text(http.StatusOK, "data") })

	req := httptest.NewRequest(http.MethodOptions, "/data", nil)
	req.Header.Set("Origin", "https://example.com")
	req.Header.Set("Access-Control-Request-Method", "POST")
	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, req)
	fmt.Println(rec.Code, rec.Header().Get("Access-Control-Allow-Origin"), rec.Header().Get("Access-Control-Allow-Methods"))
}
Output:
204 https://example.com GET,POST

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.

It needs no route, so it works on either tier — before routing, on the routed tier or on a group:

app.PreRouting(middleware.CSRF())

app.PreRouting(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 on the routed tier, a group or a route: the guard reads the matched route's meta, which exists only after the match.

app.Middleware(middleware.ContractGuard()) // every route of the App
app.POST("/users", createUser).
    SetMeta(middleware.MetaAccept, []string{"application/json"}).
    SetMeta(middleware.MetaMaxBody, 1<<20)

It fails closed without a route. Registered with App.PreRouting it sees no route on any request, so it answers 500 through the error pipeline for every request and logs one Error naming the registration and the remedy. Each contract maps a route meta key to an HTTP rejection: see the Meta* keys for the value types and status codes.

Example

ContractGuard on the routed tier enforces the contracts a route declares in its meta; each rejection carries its value in details.

package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/credo-go/credo"
	"github.com/credo-go/credo/middleware"
)

func exampleApp() *credo.App {
	app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
	if err != nil {
		panic(err)
	}
	return app
}

func exampleServe(app *credo.App, req *http.Request) {
	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, req)
	fmt.Println(req.Method, req.URL.RequestURI(), "→", rec.Code, rec.Body.String())
}

func main() {
	app := exampleApp()
	app.Middleware(middleware.ContractGuard()) // reads every route's meta; never runs for a 404 or a 405
	app.POST("/upload", func(c *credo.Context) error {
		return c.Response().NoContent(http.StatusNoContent)
	}).SetMeta(middleware.MetaAccept, []string{"application/json"}).
		SetMeta(middleware.MetaRequireHeaders, []string{"X-Tenant"})

	req := httptest.NewRequest(http.MethodPost, "/upload", strings.NewReader("<a/>"))
	req.Header.Set("Content-Type", "application/xml")
	exampleServe(app, req)

	req = httptest.NewRequest(http.MethodPost, "/upload", strings.NewReader("{}"))
	req.Header.Set("Content-Type", "application/json")
	exampleServe(app, req)

	req = httptest.NewRequest(http.MethodPost, "/upload", strings.NewReader("{}"))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Tenant", "acme")
	exampleServe(app, req)
}
Output:
POST /upload → 415 {"success":false,"error":{"code":"content_type_not_accepted","message":"Content-Type is not accepted.","details":{"content_type":"application/xml"}}}
POST /upload → 400 {"success":false,"error":{"code":"missing_required_header","message":"A required header is missing.","details":{"header":"X-Tenant"}}}
POST /upload → 204

func DefaultSkipper

func DefaultSkipper(*credo.Context) bool

DefaultSkipper never skips middleware.

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, a From pattern is malformed or has text after its catch-all, or the path of a To target has a malformed escape. A rewrite whose expanded target has a malformed escape, which only a Regexp group that splits an escape produces, returns an error.

Example

Rewrite runs before routing, so the router matches the rewritten path; a captured value keeps its wire spelling.

package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/credo-go/credo"
	"github.com/credo-go/credo/middleware"
)

func exampleApp() *credo.App {
	app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
	if err != nil {
		panic(err)
	}
	return app
}

func exampleServe(app *credo.App, req *http.Request) {
	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, req)
	fmt.Println(req.Method, req.URL.RequestURI(), "→", rec.Code, rec.Body.String())
}

func main() {
	app := exampleApp()
	app.PreRouting(middleware.Rewrite(middleware.RewriteConfig{Rules: []middleware.RewriteRule{
		{From: "/v1/{path...}", To: "/api/v1/{path}"},
	}}))
	app.GET("/api/v1/{path...}", func(c *credo.Context) error {
		return c.Response().Text(http.StatusOK, c.Request().URL.EscapedPath()+" from "+c.OriginalPath())
	})

	exampleServe(app, httptest.NewRequest(http.MethodGet, "/v1/files/a%2Fb", nil))
}
Output:
GET /api/v1/files/a%2Fb → 200 /api/v1/files/a%2Fb from /v1/files/a%2Fb

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 runs the rest of the chain in a scope whose context carries the configured deadline (credo.Context.Within): handlers and downstream calls observe it through c.Context(), and it ends when the chain returns. A value set inside the scope, such as an authenticated user, outlives it. When the chain returns context.DeadlineExceeded, the default ErrorHandler maps it to 503 request_timeout.

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 c.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
	// (c.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 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 and
	// matches as the router matches a route:
	//   - {name}       — matches one segment, up to the byte that follows
	//     the parameter in the pattern or the next slash
	//   - {name:regex} — matches one segment as {name} does, whose whole
	//     decoded value matches regex
	//   - {name...}    — matches the rest of the path, an empty rest
	//     included; it ends the pattern
	// Literal text matches only its literal spelling, as in a route pattern.
	// Ignored when Regexp is set.
	From string

	// To is the replacement path in wire form, optionally followed by a
	// query string: an escape such as "%2F" stays data, and a literal "%" is
	// written "%25". Named placeholders ({name}) are expanded with captured
	// values in wire form. A malformed escape in the path panics.
	To string

	// Regexp is an optional pre-compiled regex, matched against the
	// canonical wire path (escapes of reserved characters and of "%" kept in
	// upper-case hexadecimal, every other escape decoded); unlike a From
	// parameter, a group may span segments. When set, From is ignored. Named capture groups (?P<name>...) are used for placeholder
	// expansion; a group should capture each "%XX" escape whole.
	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.

A rule matches the request path in the canonical wire form the router matches, not the decoded URL.Path: an escaped slash ("%2F") is data inside a segment and never a separator, and an escaped reserved character ("%3B") is not its literal spelling (";"). The target is a wire-form path, and each placeholder is replaced with its capture in wire form, so the router sees after the rewrite the segments the client sent and decodes a captured value once, as it decodes a route parameter.

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 Skipper

type Skipper func(ctx *credo.Context) bool

Skipper decides whether middleware should be skipped for the current request.

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.

Directories

Path Synopsis
Package ratelimit provides token-bucket rate-limiting middleware for the Credo framework, over go-limiter's store contract.
Package ratelimit provides token-bucket rate-limiting middleware for the Credo framework, over go-limiter's store contract.

Jump to

Keyboard shortcuts

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