-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrate_limit.go
106 lines (86 loc) · 2.58 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"net/http"
"time"
"github.com/juju/ratelimit"
)
type RateLimiter interface {
Middleware
}
type RateLimiterNone struct{}
func (rl *RateLimiterNone) WrapHTTP(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
next.ServeHTTP(rw, r)
})
}
type RateLimiterHard struct {
bucket *ratelimit.Bucket
statusCode int
}
func NewRateLimiterHard(fillInterval time.Duration, capacity, quantum int64, statusCode int) *RateLimiterHard {
return &RateLimiterHard{
bucket: ratelimit.NewBucketWithQuantum(fillInterval, capacity, quantum),
statusCode: statusCode,
}
}
func (rl *RateLimiterHard) WrapHTTP(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if rl.bucket.TakeAvailable(1) == 0 {
http.Error(rw, http.StatusText(rl.statusCode), rl.statusCode)
return
}
next.ServeHTTP(rw, r)
})
}
type RateLimiterQueue struct {
bucket *ratelimit.Bucket
}
func NewRateLimiterQueue(fillInterval time.Duration, capacity, quantum int64) *RateLimiterQueue {
return &RateLimiterQueue{
bucket: ratelimit.NewBucketWithQuantum(fillInterval, capacity, quantum),
}
}
func (rl *RateLimiterQueue) WrapHTTP(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rl.bucket.Wait(1)
next.ServeHTTP(rw, r)
})
}
type RateLimiterClose struct {
bucket *ratelimit.Bucket
}
func NewRateLimiterClose(fillInterval time.Duration, capacity, quantum int64) *RateLimiterClose {
return &RateLimiterClose{
bucket: ratelimit.NewBucketWithQuantum(fillInterval, capacity, quantum),
}
}
func (rl *RateLimiterClose) WrapHTTP(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if rl.bucket.TakeAvailable(1) == 0 {
hj, ok := rw.(http.Hijacker)
if !ok {
panic("connection not hijackable") // should never happen
}
conn, _, err := hj.Hijack()
if err != nil {
http.Error(rw, fmt.Sprintf("could not hijack connection: %s", err.Error()), http.StatusInternalServerError)
return
}
conn.Close() // drop connection
return
}
next.ServeHTTP(rw, r)
})
}
type RateLimitBehavior string
const (
// no rate limit
RateLimitBehaviorNone RateLimitBehavior = "NONE"
// returns a 429 when rate is exceeded
RateLimitBehaviorHard RateLimitBehavior = "HARD"
// closes the connection if the rate is exceeded
RateLimitBehaviorClose RateLimitBehavior = "CLOSE"
// queues request until there is available capacity
RateLimitBehaviorQueue RateLimitBehavior = "QUEUE"
)