-
Notifications
You must be signed in to change notification settings - Fork 72
/
ratelimit.go
72 lines (58 loc) · 1.25 KB
/
ratelimit.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
package middleware
import (
"net/http"
"time"
"github.com/juju/ratelimit"
"github.com/gohade/hade/framework/gin"
)
var defaultRateLimit = RateLimit{
cap: 1000,
rate: 500,
waitMaxDuration: 0,
}
// RateLimit ...
type RateLimit struct {
cap int64
rate float64
waitMaxDuration time.Duration
bucket *ratelimit.Bucket
}
// RateLimitOption ...
type RateLimitOption func(r *RateLimit)
// WithRate set rate
func WithRate(rate float64) RateLimitOption {
return func(r *RateLimit) {
r.rate = rate
}
}
// WithCap set cap
func WithCap(cap int64) RateLimitOption {
return func(r *RateLimit) {
r.cap = cap
}
}
// WithWaitMaxDuration set waitMaxDuration
func WithWaitMaxDuration(max time.Duration) RateLimitOption {
return func(r *RateLimit) {
r.waitMaxDuration = max
}
}
// NewRateLimit ...
func NewRateLimit(opts ...RateLimitOption) *RateLimit {
r := defaultRateLimit
for _, opt := range opts {
opt(&r)
}
r.bucket = ratelimit.NewBucketWithRate(r.rate, r.cap)
return &r
}
// Func ...
func (r *RateLimit) Func() gin.HandlerFunc {
return func(c *gin.Context) {
if _, ok := r.bucket.TakeMaxDuration(1, r.waitMaxDuration); !ok {
c.JSON(http.StatusTooManyRequests, nil)
return
}
c.Next()
}
}