-
Notifications
You must be signed in to change notification settings - Fork 1
/
limiter.go
82 lines (65 loc) · 1.58 KB
/
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"strconv"
"time"
"github.com/go-redis/redis"
"github.com/go-redis/redis_rate"
consul "github.com/hashicorp/consul/api"
)
// FrequencyState .
type FrequencyState int
// ReqFrequency Values
const (
FrequencyStateNormal FrequencyState = 0
FrequencyStateTooHigh FrequencyState = 1
)
const KeyIPRateThreshold = "IP_RATE_THREDSHOLD"
type RedisLimiter interface {
AllowMinute(name string, maxn int64) (count int64, delay time.Duration, allow bool)
}
type SettingGetter interface {
Get(key string) ([]byte, error)
}
type ConsulKV struct {
kv *consul.KV
}
func (ck *ConsulKV) Get(key string) (value []byte, err error) {
pair, _, err := ck.kv.Get(key, nil)
if err != nil {
return nil, err
}
return pair.Value, nil
}
type IPLimit struct {
Threshold int64
SettingGetter SettingGetter
RedisLimiter RedisLimiter
}
func NewIPLimit(consulClient *consul.Client, redisClient redis.Cmdable) *IPLimit {
return &IPLimit{
SettingGetter: &ConsulKV{kv: consulClient.KV()},
RedisLimiter: redis_rate.NewLimiter(redisClient),
}
}
func (il *IPLimit) UpdateThreshold() error {
value, err := il.SettingGetter.Get(KeyIPRateThreshold)
if err != nil {
return err
}
threshold, err := strconv.Atoi(string(value))
if err != nil {
return err
}
il.Threshold = int64(threshold)
return nil
}
func (il *IPLimit) IncrFrequency(id string) (FrequencyState, error) {
if il.Threshold == 0 {
return FrequencyStateNormal, nil
}
_, _, allow := il.RedisLimiter.AllowMinute(id, il.Threshold)
if allow {
return FrequencyStateNormal, nil
}
return FrequencyStateTooHigh, nil
}