-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlimit.go
More file actions
50 lines (40 loc) · 1.25 KB
/
Copy pathlimit.go
File metadata and controls
50 lines (40 loc) · 1.25 KB
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
package main
import (
"net"
"sync"
"time"
"golang.org/x/time/rate"
)
// requestLimit and sizeLimit are the limiters. limitMutex makes sure access to them are synchronous.
var (
requestLimit = make(map[string]*rate.Limiter)
sizeLimit = make(map[string]*rate.Limiter)
limitMutex sync.Mutex
)
// hasHitRequestLimit returns if the requested remote address has reached the request limit.
func hasHitRequestLimit(remoteAddr string) bool {
ip, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
return true
}
limitMutex.Lock()
defer limitMutex.Unlock()
// Create if limiters don't exist yet.
if requestLimit[ip] == nil {
const secondsPerMinute = 60
// Initial burst is exactly one minute worth of requests.
requestLimit[ip] = rate.NewLimiter(rate.Limit(requestPerSecond), requestPerSecond*secondsPerMinute)
sizeLimit[ip] = rate.NewLimiter(rate.Limit(sizePerSecond), burstSize)
}
return !requestLimit[ip].Allow()
}
// hasHitSizeLimit returns if the requested remote address has reached the size limit.
func hasHitSizeLimit(remoteAddr string, size int64) bool {
ip, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
return true
}
limitMutex.Lock()
defer limitMutex.Unlock()
return !sizeLimit[ip].AllowN(time.Now(), int(size))
}