-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimite.go
179 lines (148 loc) · 3.92 KB
/
ratelimite.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package ratelimit
import (
"net"
"net/http"
"sync"
"time"
"github.com/yoas0bi/micro-toolkit/flowcontrol"
"github.com/yoas0bi/micro-toolkit/flowcontrol/tokenbucket"
"github.com/yoas0bi/micro-toolkit/logger"
"github.com/yoas0bi/micro-toolkit/logger/zap"
)
// NewGlobalModeLimiter todo
func NewGlobalModeLimiter(rate float64, capacity int64) *Limiter {
return new(rate, capacity, GlobalMode)
}
// NewRemoteIPModeLimiter todo
func NewRemoteIPModeLimiter(rate float64, capacity int64) *Limiter {
return new(rate, capacity, RemoteIPMode)
}
// NewHeaderKeyModeLimiter todo
func NewHeaderKeyModeLimiter(rate float64, capacity int64, headerKey string) *Limiter {
l := new(rate, capacity, HeaderKeyMode)
l.headerKey = headerKey
return l
}
// NewCookieKeyModeLimiter todo
func NewCookieKeyModeLimiter(rate float64, capacity int64, cookieKey string) *Limiter {
l := new(rate, capacity, CookieKeyMode)
l.cookieKey = cookieKey
return l
}
// New returns a new Logger instance
func new(rate float64, capacity int64, mode Mode) *Limiter {
return &Limiter{
rate: rate,
capacity: capacity,
limiters: make(map[string]flowcontrol.RateLimiter),
l: zap.L().Named("Rate Limiter"),
mode: mode,
remoteIPHeaderKey: []string{"X-Forwarded-For", "X-Real-IP"},
maxSize: 1000,
}
}
// Limiter is the structure for request rate limiter
type Limiter struct {
rate float64
capacity int64
limiters map[string]flowcontrol.RateLimiter
count int64
maxSize int64
mu sync.RWMutex
l logger.Logger
mode Mode
remoteIPHeaderKey []string
headerKey string
cookieKey string
}
// SetMaxSize 设置最大值
func (l *Limiter) SetMaxSize(max int64) {
l.maxSize = max
}
func (l *Limiter) removeExpired() int64 {
var removedCount int64
// 清理3分钟内无访问的限制器
for k, v := range l.limiters {
if time.Since(v.LastTakeTime()) > 3*time.Minute {
delete(l.limiters, k)
l.count--
removedCount++
}
}
return removedCount
}
// SetRemoteIPHeader 设置RemoteIP的头
func (l *Limiter) SetRemoteIPHeader(headers []string) {
l.remoteIPHeaderKey = headers
}
// GetLimiter 获取对应的限制器
func (l *Limiter) GetLimiter(r *http.Request) flowcontrol.RateLimiter {
id := l.getLimiterID(r)
// 获取Limiter
l.mu.RLock()
limiter, exists := l.limiters[id]
l.mu.RUnlock()
if !exists {
limiter = l.addLimiter(id)
}
return limiter
}
func (l *Limiter) addLimiter(id string) flowcontrol.RateLimiter {
l.mu.Lock()
defer l.mu.Unlock()
if l.count >= l.maxSize {
l.removeExpired()
}
limiter := tokenbucket.NewBucketWithRate(l.rate, l.capacity)
l.limiters[id] = limiter
l.count++
return limiter
}
func (l *Limiter) getLimiterID(r *http.Request) string {
switch l.mode {
case GlobalMode:
return "*"
case RemoteIPMode:
return l.remoteIP(r)
case HeaderKeyMode:
return l.headerKeyValue(r)
case CookieKeyMode:
return l.cookieKeyValue(r)
}
return ""
}
func (l *Limiter) remoteIP(r *http.Request) string {
for _, header := range l.remoteIPHeaderKey {
ip := r.Header.Get(header)
if ip != "" {
return ip
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
l.l.Errorf("get net remote ip error, %s", err)
return ""
}
return ip
}
func (l *Limiter) headerKeyValue(r *http.Request) string {
return r.Header.Get(l.headerKey)
}
func (l *Limiter) cookieKeyValue(r *http.Request) string {
ck, err := r.Cookie(l.cookieKey)
if err != nil {
l.l.Errorf("get cookie key value error, %s", err)
return ""
}
return ck.Value
}
// Handler 实现中间件
func (l *Limiter) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if !l.GetLimiter(r).TakeOneAvailable() {
http.Error(rw, http.StatusText(429), http.StatusTooManyRequests)
return
}
next.ServeHTTP(rw, r)
})
}