Documentation
¶
Overview ¶
Package rate implements a token-bucket rate limiter for incoming requests, one bucket per client.
Its entry point is New(limit, burst, Options), which returns a *Limiter rather than a Handler: the limiter owns a background purge goroutine and must be stopped with Stop when it is no longer needed, and it exposes the clients map to `Get`. Register `Limiter.Handler()` on a Router or a Route, or use the `Limit` one-liner when the limiter lives for the whole process.
Example can be found at: _examples/06-middleware/rate-limit/main.go.
Index ¶
Constants ¶
const Inf = math.MaxFloat64
Inf is the infinite rate limit; it allows all events (even if burst is zero).
Variables ¶
var DefaultExceedHandler = func(ctx *context.Context) {
ctx.StopWithStatus(429)
}
DefaultExceedHandler is the default handler which is being used when Options.ExceedHandler is not set. It stops the execution with status code 429 (Too Many Requests).
Functions ¶
func Every ¶
Every converts a minimum time interval between events to a limit. Usage: Limit(Every(1*time.Minute), 3, Options{})
func Limit ¶
Limit returns a new rate limiter handler that allows requests up to rate "limit" and permits bursts of at most "burst" tokens. See `rate.SetIdentifier(ctx, key string)` and `rate.Get` too.
E.g. Limit(1, 5, rate.Options{}) to allow 1 request per second, with a maximum burst size of 5.
It is shorthand for New(limit, burst, opts).Handler(): the Limiter itself is discarded and its purge goroutine runs for the lifetime of the process, which is correct for process-lifetime middleware. Use `New` when the limiter must be stopped, e.g. on tests or reloadable configurations.
func RegisterExceedHandler ¶
RegisterExceedHandler sets a middleware which sets the exceed "handler" for the current Router. The "handler" will be executed every time a client tries to reach a page/resource which is not accessible for that moment.
func SetIdentifier ¶
SetIdentifier can be called manually from a handler or a middleare to change the identifier per client. The default key for a client is its Remote IP.
Types ¶
type Client ¶
type Client struct {
ID string
Data any
Limiter *rate.Limiter
// Delay indicates, when the limit was exceeded, how long the client must
// wait before the resource becomes available again.
//
// Read it through RetryDelay: this value is written under mu by whichever
// request hit the limit, and a Client is shared by every concurrent
// request from the same identifier.
Delay time.Duration
// contains filtered or unexported fields
}
Client holds some request information and the rate limiter itself. It can be retrieved by the `Get` package-level function. It can be used to manually add RateLimit response headers.
func Get ¶
Get returns the current rate limited `Client`. Use it when you want to log or add response headers based on the current request limitation.
You can read more about X-RateLimit response headers at: https://tools.ietf.org/id/draft-polli-ratelimit-headers-00.html. A good example of that is the GitHub API itself: https://developer.github.com/v3/#rate-limiting
func (*Client) DurationFromTokens ¶
DurationFromTokens is a unit conversion function from the number of tokens to the duration of time it takes to accumulate them at a rate of limit tokens per second.
func (*Client) RetryDelay ¶
RetryDelay returns how long the client must wait before the resource becomes available again, or zero when the last request was not rate limited.
Use this instead of reading the Delay field directly: a Client is shared by every concurrent request from the same identifier, and Delay is written under the client's mutex. Reading it unlocked - which is what building "X-RateLimit-*" headers from rate.Get(ctx).Delay does - is a data race.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter is featured with the necessary functions to limit requests per second. It is created through the `New` package-level function (or, indirectly, through `Limit`). Register its `Handler` and call `Stop` when the limiter is no longer needed, to release its background purge goroutine.
func New ¶
New returns a new Limiter which allows requests up to rate "limit" and permits bursts of at most "burst" tokens. Register its `Handler` and call `Stop` when the limiter is no longer needed. See `Limit` for the one-liner version and `Options` for the optional configuration.
func (*Limiter) Handler ¶
Handler returns the limiter's middleware handler, ready to be registered on a Router or a Route.
func (*Limiter) Purge ¶
Purge removes client entries from the memory based on the given "condition".
func (*Limiter) Stop ¶
func (l *Limiter) Stop()
Stop terminates the limiter's background purge goroutine and waits for it to exit; after Stop returns no purge runs anymore (already-stored clients remain until garbage collected with the Limiter itself). It is safe to call Stop more than once and from concurrent goroutines.
type Options ¶
type Options struct {
// ExceedHandler is executed every time a client tries to reach a
// page/resource which is not accessible for that moment.
// This sets the handler for all requests. To override it for the requests of
// a specific Router, use the `RegisterExceedHandler` package-level function.
//
// Defaults to DefaultExceedHandler, which stops with 429 (Too Many Requests).
ExceedHandler context.Handler
// ClientData provides custom data that will be stored on the Client and can
// be retrieved as `Get(ctx).Data` later on.
//
// Defaults to nil.
ClientData func(ctx *context.Context) any
// PurgeEvery is how often old client entries are checked and removed,
// e.g. PurgeEvery: time.Minute and PurgeMaxLifetime: 5*time.Minute to check
// every minute whether a client's last visit was 5 minutes ago and drop it
// from the memory.
//
// Defaults to one minute. There is always a purger, because a limiter
// without one grows forever - see the note in `New`.
//
// PurgeEvery and PurgeMaxLifetime are independent: setting one alone leaves
// the other at its default.
PurgeEvery time.Duration
// PurgeMaxLifetime is how long a client entry with no request is kept.
//
// Defaults to a value derived from the rate, long enough that dropping an
// entry can never hand a client a burst it had not already earned.
// See PurgeEvery.
PurgeMaxLifetime time.Duration
}
Options holds the optional configuration of a Limiter. The zero value is valid and uses the documented defaults.