Documentation
¶
Overview ¶
Package ratelimit provides a sliding-window HTTP rate limiter middleware.
Requests that exceed the limit receive a 429 Too Many Requests response with standard X-RateLimit-* and Retry-After headers. The rate-limiting key defaults to the client IP address but is fully configurable.
Quick start:
store := ratelimit.NewMemoryStore()
limiter := ratelimit.New(store, ratelimit.Config{
Limit: 100,
Window: time.Minute,
})
mux.Handle("/api/", limiter(apiHandler))
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ByRoute ¶
ByRoute returns a KeyFn that combines the client IP with the URL path, allowing different limits per route without separate middleware instances.
Types ¶
type Config ¶
type Config struct {
// Limit is the maximum number of requests allowed within Window.
Limit int64
// Window is the sliding-window duration (e.g. time.Minute).
Window time.Duration
// KeyFn derives the rate-limit key from the request.
// Defaults to the client's remote IP address when nil.
KeyFn func(r *http.Request) string
// OnLimited is called when a request is rejected.
// Defaults to a JSON 429 response when nil.
OnLimited func(w http.ResponseWriter, r *http.Request, reset time.Time)
}
Config configures a rate limiter middleware instance.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is a thread-safe, in-process Store implementation using a sliding-window counter algorithm. It is suitable for single-process deployments. For horizontally-scaled services use a shared store (e.g. Redis).
func NewMemoryStore ¶
func NewMemoryStore() *MemoryStore
NewMemoryStore returns an initialised MemoryStore.
func (*MemoryStore) Reset ¶
func (s *MemoryStore) Reset(key string) error
type Store ¶
type Store interface {
// Inc atomically increments the counter for key within the given window and
// returns the current count. The store must expire the key after window elapses.
Inc(key string, window time.Duration) (count int64, err error)
// Reset clears the counter for key immediately.
Reset(key string) error
}
Store is the backend for tracking request counts. Implement this interface to back the rate limiter with Redis, Memcached, etc.