blob: b088fbc2c81a4ca9b4c05e93dcd8fd08c58fbd2e (
plain)
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
|
package main
import (
"sync"
"time"
)
// RateLimiter is a fixed-window per-key request limiter: at most max
// requests per key within each window. Keys are client IPs. It is the
// "max requests per minute" anti-abuse guard; excess requests are denied
// until the current window rolls over. State is in memory only.
type RateLimiter struct {
mu sync.Mutex
max int
window time.Duration
visitors map[string]*visitor
lastGC time.Time
}
type visitor struct {
count int
resetAt time.Time
}
func NewRateLimiter(max int, window time.Duration) *RateLimiter {
if max < 1 {
max = 1
}
if window <= 0 {
window = time.Minute
}
return &RateLimiter{max: max, window: window, visitors: make(map[string]*visitor)}
}
// Allow reports whether key may make one more request. If not, it returns
// how long the caller should wait before retrying.
func (rl *RateLimiter) Allow(key string) (bool, time.Duration) {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
v, ok := rl.visitors[key]
if !ok || now.After(v.resetAt) {
v = &visitor{count: 0, resetAt: now.Add(rl.window)}
rl.visitors[key] = v
}
if now.Sub(rl.lastGC) > rl.window {
for k, e := range rl.visitors {
if now.After(e.resetAt) {
delete(rl.visitors, k)
}
}
rl.lastGC = now
}
if v.count >= rl.max {
return false, time.Until(v.resetAt)
}
v.count++
return true, 0
}
|