Documentation
¶
Overview ¶
Package ratelimit provides stable rate-limit middleware over ports.RateLimiter.
The middleware owns HTTP behavior while storage and quota decisions stay behind the RateLimiter port. Use contrib adapters for concrete stores, and keep dangerous local bypass configuration restricted to trusted proxies.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SetRateLimitHeaders ¶
func SetRateLimitHeaders(w http.ResponseWriter, quota Quota, config HeaderConfig)
SetRateLimitHeaders writes standard quota headers when config is enabled.
func WriteRateLimited ¶
func WriteRateLimited(w http.ResponseWriter, decision Decision, config HeaderConfig)
WriteRateLimited writes a 429 Problem Details response with quota headers.
Types ¶
type HeaderConfig ¶
type HeaderConfig struct {
Enabled bool
LimitHeader string
RemainingHeader string
ResetHeader string
RetryAfterHeader string
}
HeaderConfig configures standard rate-limit response headers.
func DefaultHeaderConfig ¶
func DefaultHeaderConfig() HeaderConfig
DefaultHeaderConfig returns enabled RFC-compatible quota header names.
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware enforces in-memory token bucket rate limits.
func New ¶
func New(opts Options) (*Middleware, error)
New constructs a rate limiting middleware with defaults.
func (*Middleware) Handler ¶
func (m *Middleware) Handler(next http.Handler) http.Handler
Handler wraps the next handler with rate limiting logic.
func (*Middleware) Middleware ¶
func (m *Middleware) Middleware() func(http.Handler) http.Handler
Middleware implements ports.Middleware via Handler adapter.
type Options ¶
type Options struct {
Capacity float64 // tokens
RefillRate float64 // tokens per second
Key KeyFn // how to key buckets
RetryAfter time.Duration
Clock ports.Clock
// Limiter overrides the default in-memory limiter with a shared limiter.
Limiter ports.RateLimiter
// ClientIPResolver derives client identity from trusted proxies.
ClientIPResolver identity.Resolver
// StateTTL evicts buckets that have been idle for this duration.
StateTTL time.Duration
// CleanupInterval controls how often eviction runs.
CleanupInterval time.Duration
// SkipEnabled toggles honoring the SkipHeader. Useful for tests/dev.
SkipEnabled bool
// SkipHeader contains the header name that, when present, bypasses limiting.
// When empty, no bypass is applied.
SkipHeader string
// AllowDangerousDevBypasses enables skip headers only when request comes from trusted proxies.
AllowDangerousDevBypasses bool
// FailOpen controls whether requests pass through when limiter errors.
FailOpen bool
// OnError receives limiter errors, when present.
OnError func(error)
// HeaderConfig enables standard RateLimit-* response headers when configured.
HeaderConfig HeaderConfig
}
Options configures the rate limit middleware.