forked from ahmedash95/ratelimit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate_limit.go
85 lines (75 loc) · 1.4 KB
/
rate_limit.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
83
84
85
package ratelimit
import (
"fmt"
"sync"
"time"
)
type Limit struct {
MaxRequests int
Per time.Duration
Block time.Duration
Blocker Blocker
MaxSpam int
Spammer Spammer
Rates map[string]*RateLimit
}
type RateLimit struct {
ExpiredAt time.Time
Hits int
}
var (
Mutex sync.Mutex
)
func CreateLimit(key string) Limit {
op, err := parse(key)
if err != nil {
panic(fmt.Sprintf("Faild to parse %s : %q", key, err))
}
limits := make(map[string]*RateLimit)
l := Limit{
MaxRequests: op.Max,
Per: op.Per,
Block: op.Block,
MaxSpam: op.MaxToSpam,
Rates: limits,
}
RunLimitCleaner(&l)
if l.MaxSpam != 0 {
l.Spammer = CreateSpammer()
}
if l.Block != 0 {
l.Blocker = CreateBlocker()
}
return l
}
func createKey() *RateLimit {
return &RateLimit{
ExpiredAt: time.Now(),
}
}
func (l *Limit) Hit(key string) error {
Mutex.Lock()
k, ok := l.Rates[key]
if !ok {
l.Rates[key] = createKey()
k = l.Rates[key]
}
if k.Hits >= l.MaxRequests {
if l.Spammer.Values != nil {
l.Spammer.Increase(key)
}
if l.Spammer.Values != nil && l.Blocker.Values != nil {
if l.Spammer.Values[key].Hits >= l.MaxSpam {
l.Blocker.AddIfNotExists(key)
}
}
Mutex.Unlock()
return fmt.Errorf("The key [%s] has reached max requests [%d]", key, k.Hits)
}
k.Hit()
Mutex.Unlock()
return nil
}
func (r *RateLimit) Hit() {
r.Hits += 1
}