Skip to main content

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

// WithLimiter set Limiter implementation,
// default is bbr limiter
func WithLimiter(limiter ratelimit.Limiter) Option {
return func(o *options) {
o.limiter = limiter
}
}

The costom limiter nneds to implement the Limiter interface of aegis/ratelimit.

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

Usage

Use rate limiter in Server

var opts = []http.ServerOption{
http.Middleware(
ratelimit.Server(),
),
}

srv := http.NewServer(opts...)

Trigger rate limiter

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

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