-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrate_limiter.go
64 lines (54 loc) · 1.32 KB
/
rate_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
package chill
import (
"net"
"net/http"
"time"
)
type keyGenerator func(r *http.Request) string
type RateLimiter struct {
window time.Duration
max int
statusCode int
message string
storage *storage
keyGen keyGenerator
}
func NewRateLimiter(window time.Duration, max int) *RateLimiter {
lim := RateLimiter{
window: window,
max: max,
statusCode: 429,
message: "Too many requests, please try again later",
storage: newStorage(window),
keyGen: func(r *http.Request) string {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
uip := net.ParseIP(ip)
if uip == nil {
return ""
}
return uip.String()
},
}
return &lim
}
func (lim *RateLimiter) RateLimit(next func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
key := lim.keyGen(r)
cur := lim.storage.increment(key)
if cur > lim.max {
w.Header().Set("Retry-After", (lim.window / time.Second).String())
http.Error(w, lim.message, lim.statusCode)
return
}
next(w, r)
}
}
func (lim *RateLimiter) SetStatusCode(statusCode int) {
lim.statusCode = statusCode
}
func (lim *RateLimiter) SetMessage(message string) {
lim.message = message
}
func (lim *RateLimiter) SetKeyGenerator(keyGen keyGenerator) {
lim.keyGen = keyGen
}