Documentation
¶
Overview ¶
Package middleware provides HTTP middleware components for the cdev server.
Index ¶
Constants ¶
const ( DefaultMaxRequests = 10 // Max requests per window DefaultWindow = 1 * time.Minute // Time window for rate limiting DefaultCleanup = 5 * time.Minute // Cleanup interval for stale buckets )
RateLimiter configuration constants.
Variables ¶
var TrustProxy = false
TrustProxy controls whether to trust X-Forwarded-For headers. Set to true only when behind a trusted reverse proxy.
Functions ¶
func IPKeyExtractor ¶
IPKeyExtractor extracts the client IP address as the rate limit key. WARNING: X-Forwarded-For headers are only trusted when TrustProxy is true. Without a trusted proxy, these headers can be spoofed to bypass rate limiting.
func RateLimitMiddleware ¶
func RateLimitMiddleware(limiter *RateLimiter, keyExtractor KeyExtractor) func(http.Handler) http.Handler
RateLimitMiddleware returns an HTTP middleware that applies rate limiting.
Types ¶
type KeyExtractor ¶
KeyExtractor is a function that extracts a rate limit key from a request.
func HeaderKeyExtractor ¶
func HeaderKeyExtractor(header string) KeyExtractor
HeaderKeyExtractor creates a key extractor that uses a specific header value.
func NewTrustedProxyIPKeyExtractor ¶
func NewTrustedProxyIPKeyExtractor(trustedProxies []*net.IPNet) KeyExtractor
NewTrustedProxyIPKeyExtractor returns an extractor that trusts forwarded headers only when the remote address belongs to one of the trusted proxies.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a sliding window rate limiter with per-key limiting.
func NewRateLimiter ¶
func NewRateLimiter(opts ...RateLimiterOption) *RateLimiter
NewRateLimiter creates a new RateLimiter with the given options.
func (*RateLimiter) Allow ¶
func (r *RateLimiter) Allow(key string) bool
Allow checks if a request from the given key is allowed. Returns true if allowed, false if rate limited.
func (*RateLimiter) Remaining ¶
func (r *RateLimiter) Remaining(key string) int
Remaining returns the number of remaining requests for a key.
func (*RateLimiter) Reset ¶
func (r *RateLimiter) Reset(key string)
Reset clears the rate limit for a key.
type RateLimiterOption ¶
type RateLimiterOption func(*RateLimiter)
RateLimiterOption is a functional option for configuring RateLimiter.
func WithMaxRequests ¶
func WithMaxRequests(n int) RateLimiterOption
WithMaxRequests sets the maximum number of requests per window.
func WithWindow ¶
func WithWindow(d time.Duration) RateLimiterOption
WithWindow sets the time window for rate limiting.