Documentation
¶
Overview ¶
Package ratelimit provides HTTP rate limiting middleware using token buckets.
It tracks per-IP request rates with LRU eviction when the IP map is full. For high-concurrency workloads, a sharded implementation reduces lock contention by distributing IPs across multiple mutex-guarded maps.
Usage:
rl := ratelimit.New(ctx,
ratelimit.WithRate(10),
ratelimit.WithBurst(20),
)
defer rl.Close()
handler := rl.Middleware()(mux)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetClientIP ¶
GetClientIP extracts the client IP from the request. It only trusts X-Forwarded-For / X-Real-IP when the immediate peer is a loopback or private address (i.e., behind a reverse proxy). This is correct when deployed behind a single trusted reverse proxy. In multi-tenant private networks, consider configuring trusted proxy CIDRs explicitly.
Types ¶
type Config ¶
type Config struct {
RPS float64
Burst int
MaxIPs int
DenyHandler http.HandlerFunc
SweepInterval time.Duration
StaleThreshold time.Duration
EvictLogInterval time.Duration
}
Config holds rate limiter configuration.
type Option ¶
type Option func(*Config)
Option configures a Config.
func WithDenyHandler ¶
func WithDenyHandler(h http.HandlerFunc) Option
WithDenyHandler sets a custom handler for rate-limited requests.
func WithEvictLogInterval ¶
WithEvictLogInterval sets the minimum time between eviction log messages.
func WithMaxIPs ¶
WithMaxIPs sets the maximum number of unique IPs to track.
func WithStaleThreshold ¶
WithStaleThreshold sets how long an IP must be idle before cleanup removes it.
func WithSweepInterval ¶
WithSweepInterval sets how often stale entries are cleaned up.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter manages per-IP rate limiting with LRU eviction.
func New ¶
func New(ctx context.Context, opts ...Option) *RateLimiter
New creates a RateLimiter that runs a background cleanup goroutine. The goroutine is stopped when Close is called or ctx is cancelled.
For MaxIPs >= 16, a sharded implementation is used to reduce lock contention. For smaller values, a single-mutex implementation is used.
func (*RateLimiter) Close ¶
func (rl *RateLimiter) Close()
Close stops the cleanup goroutine and waits for it to exit.
func (*RateLimiter) Middleware ¶
func (rl *RateLimiter) Middleware() func(http.Handler) http.Handler
Middleware returns the HTTP middleware function.