Documentation
¶
Index ¶
- Constants
- type RateLimiter
- func (r *RateLimiter) CheckCooldown(ctx context.Context, key string, cooldown time.Duration) (bool, time.Time, error)
- func (r *RateLimiter) CheckDestinationLimit(ctx context.Context, destination string, limit int, window time.Duration) (bool, int, time.Time, error)
- func (r *RateLimiter) CheckIPLimit(ctx context.Context, ip string, limit int, window time.Duration) (bool, int, time.Time, error)
- func (r *RateLimiter) CheckLimit(ctx context.Context, key string, limit int, window time.Duration) (bool, int, time.Time, error)
- func (r *RateLimiter) CheckUserLimit(ctx context.Context, userID string, limit int, window time.Duration) (bool, int, time.Time, error)
Examples ¶
Constants ¶
const ( // DefaultKeyPrefix is the default prefix for rate limit keys DefaultKeyPrefix = "ratelimit:" // DefaultCooldownPrefix is the default prefix for cooldown keys DefaultCooldownPrefix = "ratelimit:cooldown:" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter provides rate limiting functionality using Redis
func NewRateLimiter ¶
func NewRateLimiter(client redis.UniversalClient) *RateLimiter
NewRateLimiter creates a new rate limiter with default prefixes.
client is a redis.UniversalClient, so *redis.Client, *redis.ClusterClient, *redis.Ring and a Sentinel-backed failover client all work here.
Both scripts are single-key, so they run unchanged on a cluster: every key a call touches is the one key it was given, and no cross-slot command is ever issued.
Example (ClusterClient) ¶
NewRateLimiter takes a redis.UniversalClient. Both scripts are single-key, so they run unchanged on a cluster -- nothing here is cross-slot. Compiled but not run: there is no cluster here.
package main
import (
"context"
"time"
"github.com/redis/go-redis/v9"
"github.com/soulteary/redis-kit/ratelimit"
)
func main() {
cluster := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{"10.0.0.1:6379", "10.0.0.2:6379", "10.0.0.3:6379"},
})
defer func() { _ = cluster.Close() }()
limiter := ratelimit.NewRateLimiter(cluster)
_, _, _, _ = limiter.CheckIPLimit(context.Background(), "203.0.113.7", 100, time.Minute)
}
Output:
func NewRateLimiterWithPrefixes ¶
func NewRateLimiterWithPrefixes(client redis.UniversalClient, keyPrefix, cooldownPrefix string) *RateLimiter
NewRateLimiterWithPrefixes creates a new rate limiter with custom prefixes
func (*RateLimiter) CheckCooldown ¶
func (r *RateLimiter) CheckCooldown(ctx context.Context, key string, cooldown time.Duration) (bool, time.Time, error)
CheckCooldown checks if resend is allowed (cooldown period) Returns (allowed, resetTime, error)
Example ¶
A cooldown is the "one message per interval" rule: the first call takes it, the rest are refused until it elapses.
package main
import (
"context"
"fmt"
"time"
"github.com/soulteary/redis-kit/ratelimit"
"github.com/soulteary/redis-kit/testutil"
)
func main() {
client, _ := testutil.NewMockRedisClient()
defer func() { _ = client.Close() }()
limiter := ratelimit.NewRateLimiter(client)
ctx := context.Background()
first, _, err := limiter.CheckCooldown(ctx, "sms:+10000000000", time.Minute)
if err != nil {
fmt.Println("cooldown:", err)
return
}
second, _, _ := limiter.CheckCooldown(ctx, "sms:+10000000000", time.Minute)
fmt.Println("first:", first)
fmt.Println("second:", second)
}
Output: first: true second: false
func (*RateLimiter) CheckDestinationLimit ¶
func (r *RateLimiter) CheckDestinationLimit(ctx context.Context, destination string, limit int, window time.Duration) (bool, int, time.Time, error)
CheckDestinationLimit checks rate limit for a destination (phone/email)
func (*RateLimiter) CheckIPLimit ¶
func (r *RateLimiter) CheckIPLimit(ctx context.Context, ip string, limit int, window time.Duration) (bool, int, time.Time, error)
CheckIPLimit checks rate limit for an IP address
func (*RateLimiter) CheckLimit ¶
func (r *RateLimiter) CheckLimit(ctx context.Context, key string, limit int, window time.Duration) (bool, int, time.Time, error)
CheckLimit checks if a request should be rate limited Returns (allowed, remaining, resetTime, error)
Example ¶
A fixed window counted in Redis, so the limit holds across every instance of the service rather than per process.
package main
import (
"context"
"fmt"
"time"
"github.com/soulteary/redis-kit/ratelimit"
"github.com/soulteary/redis-kit/testutil"
)
func main() {
client, _ := testutil.NewMockRedisClient() // in real code, your own client
defer func() { _ = client.Close() }()
limiter := ratelimit.NewRateLimiter(client)
ctx := context.Background()
for i := 0; i < 4; i++ {
allowed, remaining, _, err := limiter.CheckLimit(ctx, "user:1", 3, time.Minute)
if err != nil {
fmt.Println("check:", err)
return
}
fmt.Printf("request %d: allowed=%v remaining=%d\n", i+1, allowed, remaining)
}
}
Output: request 1: allowed=true remaining=2 request 2: allowed=true remaining=1 request 3: allowed=true remaining=0 request 4: allowed=false remaining=0