Documentation
¶
Overview ¶
Package ratelimit provides request rate limiting / throttling for togo apps.
It uses a token-bucket limiter: each key (an IP, user, route, or anything you choose) gets a bucket of Limit tokens that refills continuously over Window. A request consumes one token; when the bucket is empty the request is denied with a Retry-After hint. Use it as HTTP middleware or call Allow directly.
s, _ := ratelimit.FromKernel(k)
api := s.Middleware(ratelimit.Rate("api", 60, time.Minute), nil) // 60/min per IP
r.With(api).Get("/things", handler)
Index ¶
- func ClientIP(r *http.Request) string
- type KeyFunc
- type Policy
- type Service
- func (s *Service) Allow(_ context.Context, key string, p Policy) (allowed bool, retryAfter time.Duration)
- func (s *Service) Define(p Policy)
- func (s *Service) Middleware(p Policy, keyFn KeyFunc) func(http.Handler) http.Handler
- func (s *Service) Policy(name string) (Policy, bool)
- func (s *Service) WithStore(store Store) *Service
- type Store
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Policy ¶
type Policy struct {
Name string `json:"name"`
Limit int `json:"limit"`
Window time.Duration `json:"window"`
}
Policy is a rate limit: at most Limit requests per Window (also the burst).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the rate-limit runtime stored on the kernel (k.Get("ratelimit")).
func FromKernel ¶
FromKernel returns the rate-limit Service registered on the kernel.
func (*Service) Allow ¶
func (s *Service) Allow(_ context.Context, key string, p Policy) (allowed bool, retryAfter time.Duration)
Allow reports whether a request under key is permitted by policy p. When denied it returns the duration to wait before retrying.
func (*Service) Middleware ¶
Middleware enforces policy p, keyed by keyFn (defaults to ClientIP). It sets the standard X-RateLimit-* headers and responds 429 with Retry-After when the limit is exceeded.
type Store ¶
type Store interface {
// Take attempts to consume one token for key under policy p at time now.
// It returns whether the request is allowed, the tokens remaining, and the
// time at which a token will next be available (the reset).
Take(key string, p Policy, now time.Time) (allowed bool, remaining int, reset time.Time)
}
Store holds per-key limiter state. The default is in-memory; implement this to back the limiter with Redis (via the cache plugin) for multi-instance use.