-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken-bucket.go
44 lines (33 loc) · 993 Bytes
/
token-bucket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main
import (
"time"
"context"
"strconv"
"github.com/go-redis/redis/v8"
)
func TokenBucketRateLimit(
ctx context.Context, redisClient *redis.Client,
userId string, refillWindow int64, maximumTokens int64) bool {
tokenKey := "token"
lastRefillTimeKey := "last_refill_time"
tokenBucket := "rate_limiting:" + userId
tokenCountStr := redisClient.HGet(ctx, tokenBucket, tokenKey)
lastRefillTimeStr := redisClient.HGet(ctx, tokenBucket, lastRefillTimeKey)
tokenCount, _ := strconv.ParseInt(tokenCountStr.Val(), 10, 64)
lastRefillTime, _ := strconv.ParseInt(lastRefillTimeStr.Val(), 10, 64)
currentTime := time.Now().Unix()
timeElapsed := currentTime - lastRefillTime
if timeElapsed >= refillWindow {
tokenCount = maximumTokens
lastRefillTime = currentTime
}
if tokenCount <= 0 {
return false
}
tokenCount--
redisClient.HSet(ctx, tokenBucket, map[string]interface{}{
tokenKey: tokenCount,
lastRefillTimeKey: currentTime,
}).Val()
return true
}