-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrate_limiter.go
57 lines (51 loc) · 1005 Bytes
/
rate_limiter.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
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"context"
"errors"
"fmt"
"strconv"
"time"
)
const (
MaxAttempts = 100
RateLimiterTTL = time.Hour
)
type RateLimiter struct {
store Store
}
func NewRateLimiter(store Store) *RateLimiter {
return &RateLimiter{
store: store,
}
}
func (r *RateLimiter) KeyValue(key string) string {
return fmt.Sprintf("rate_limiter:%s", key)
}
func (r *RateLimiter) IsRateLimited(ctx context.Context, key string) (bool, error) {
key = r.KeyValue(key)
currentValue, err := r.store.Get(ctx, key)
if err != nil && !errors.Is(err, ErrKeyNotFound) {
return false, err
}
if string(currentValue) == "" {
currentValue = []byte("0")
}
count, err := strconv.Atoi(string(currentValue))
if err != nil {
return false, err
}
if count >= MaxAttempts {
return true, nil
}
val, err := r.store.Incr(ctx, key)
if err != nil {
return false, err
}
if val == 1 {
err = r.store.Expire(ctx, key, RateLimiterTTL)
if err != nil {
return false, err
}
}
return false, nil
}