Documentation
¶
Overview ¶
Package ratelimit is a Redis-backed token-bucket rate limiter with per-key buckets, cost-per-request, and a Fiber middleware.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter is a token-bucket rate limiter backed by Redis.
func New ¶
func New(client redis.UniversalClient, opts ...Option) *Limiter
New returns a Limiter using the given Redis client.
func (*Limiter) Allow ¶
Allow attempts to consume cost tokens for key under rule.
Example ¶
A token bucket of 2 with a slow refill: the first two requests pass, the third is denied.
package main
import (
"context"
"fmt"
"github.com/alicebob/miniredis/v2"
goredis "github.com/redis/go-redis/v9"
"github.com/rahmadafandi/fibr/ratelimit"
)
func main() {
mr, _ := miniredis.Run()
defer mr.Close()
client := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
defer func() { _ = client.Close() }()
l := ratelimit.New(client)
rule := ratelimit.Rule{Capacity: 2, RefillPerSec: 1}
ctx := context.Background()
for range 3 {
res, _ := l.Allow(ctx, "user:1", rule, 1)
fmt.Println(res.Allowed)
}
}
Output: true true false
func (*Limiter) Middleware ¶
Middleware limits requests per key under rule (cost 1 each). keyFunc derives the bucket key; when nil it uses the client IP. On a deny it responds 429 with Retry-After and X-RateLimit-* headers. A Redis error fails open (the request is allowed) so the limiter cannot take the app down.
type Option ¶ added in v1.6.0
type Option func(*Limiter)
Option configures a Limiter.
func WithLogger ¶ added in v1.6.0
WithLogger sets the logger Middleware reports Redis failures to. The default is logger.Default().