-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlimiter.go
76 lines (63 loc) · 2.25 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
package gorillimiter
import (
"log"
"net/http"
"time"
)
// MiddlewareWrapper can be used for chained middleware
func MiddlewareWrapper(requestsPerInterval int, interval time.Duration) func(http.Handler) http.Handler {
cache, err := NewLRU(1000, interval)
if err != nil {
log.Println("Couldn't create a cache - falling back to passthrough", err)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
next.ServeHTTP(wr, req)
})
}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
ip := getRemoteIP(req)
// Set a maximum of requestsPerInterval requests per interval
cnt, underRateLimit := cache.Inc(ip, requestsPerInterval)
if underRateLimit {
// we good son
next.ServeHTTP(wr, req)
return
}
log.Printf("Address [%s] is over ratelimit, denying for now, current hits [%d]\n", ip, cnt)
http.Error(wr, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
return
})
}
}
// Limiter is the an LRU based limiter for a gorilla mux
// It's hardcoded to only remember most recent 1000 IP addresses
// You choose how many requests are allowed per interval
func Limiter(next http.Handler, requestsPerInterval int, interval time.Duration) http.Handler {
// This is only called once per limiter
// We'll only cache upto 1000 IP addresses
// And set the window to flush every $interval seconds
// with a max of $requestsPerInterval per $interval
cache, err := NewLRU(1000, interval)
if err != nil {
log.Println("Couldn't create a cache - falling back to passthrough", err)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
return
})
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := getRemoteIP(r)
// Set a maximum of requestsPerInterval requests per interval
cnt, underRateLimit := cache.Inc(ip, requestsPerInterval)
if underRateLimit {
// we good son
next.ServeHTTP(w, r)
return
}
log.Printf("Address [%s] is over ratelimit, denying for now, current hits [%d]\n", ip, cnt)
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
return
})
}