-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate_limit.go
82 lines (66 loc) · 1.38 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
package main
import (
"golang.org/x/time/rate"
"sync"
"time"
)
// IPRateLimiter .
type IPRateLimiter struct {
ips map[string]*LimiterEntry
mu *sync.RWMutex
r rate.Limit
b int
}
type LimiterEntry struct {
limiter *rate.Limiter
lastUse time.Time
}
// NewIPRateLimiter .
func NewIPRateLimiter(r rate.Limit, b int) *IPRateLimiter {
i := &IPRateLimiter{
ips: make(map[string]*LimiterEntry),
mu: &sync.RWMutex{},
r: r,
b: b,
}
go func() {
for range time.Tick(time.Second * 30) {
i.mu.Lock()
for s := range i.ips {
l := i.ips[s]
var diff = time.Now().Sub(l.lastUse).Seconds()
if diff > 10 {
delete(i.ips, s)
}
}
i.mu.Unlock()
}
}()
return i
}
// AddIP creates a new rate limiter and adds it to the ips map,
// using the IP address as the key
func (i *IPRateLimiter) AddIP(ip string) *rate.Limiter {
i.mu.Lock()
defer i.mu.Unlock()
limiter := rate.NewLimiter(i.r, i.b)
le := &LimiterEntry{
limiter: limiter,
lastUse: time.Now(),
}
i.ips[ip] = le
return limiter
}
// GetLimiter returns the rate limiter for the provided IP address if it exists.
// Otherwise calls AddIP to add IP address to the map
func (i *IPRateLimiter) GetLimiter(ip string) *rate.Limiter {
i.mu.Lock()
limiter, exists := i.ips[ip]
if !exists {
i.mu.Unlock()
return i.AddIP(ip)
}
limiter.lastUse = time.Now()
i.mu.Unlock()
return limiter.limiter
}