Rate Limiter

Rate limiter middleware for server-side traffic control, with bbr limiter algorithm implemented by default.

Configuration

WithLimiter

Used to replace the default limiter algorithm

  1. // WithLimiter set Limiter implementation,
  2. // default is bbr limiter
  3. func WithLimiter(limiter ratelimit.Limiter) Option {
  4. return func(o *options) {
  5. o.limiter = limiter
  6. }
  7. }

The custom limiter needs to implement the Limiter interface of aegis/ratelimit.

  1. // Limiter is a rate limiter.
  2. type Limiter interface {
  3. Allow() (DoneFunc, error)
  4. }

Usage

Use rate limiter in Server

  1. var opts = []http.ServerOption{
  2. http.Middleware(
  3. // default is bbr limiter
  4. ratelimit.Server(),
  5. // custom limiter
  6. //ratelimit.Server(ratelimit.WithLimiter(limiter)),
  7. ),
  8. }
  9. srv := http.NewServer(opts...)

Trigger rate limiter

When the rate limiter is triggered, the current request is rejected directly and error ErrLimitExceed will be returned, as defined below:

  1. // ErrLimitExceed is service unavailable due to rate limit exceeded.
  2. var ErrLimitExceed = errors.New(429, "RATELIMIT", "service unavailable due to rate limit exceeded")