-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
202 lines (161 loc) · 4.35 KB
/
main.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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package echo_limiter
import (
"errors"
"net/http"
"strconv"
"time"
"github.com/go-redis/redis/v7"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/shareed2k/go_limiter"
)
const (
SlidingWindowAlgorithm = go_limiter.SlidingWindowAlgorithm
GCRAAlgorithm = go_limiter.GCRAAlgorithm
DefaultKeyPrefix = "echo_limiter"
defaultMessage = "Too many requests, please try again later."
defaultStatusCode = http.StatusTooManyRequests
)
var (
DefaultConfig = Config{
Skipper: middleware.DefaultSkipper,
Max: 10,
Burst: 10,
StatusCode: defaultStatusCode,
Message: defaultMessage,
Prefix: DefaultKeyPrefix,
Algorithm: SlidingWindowAlgorithm,
Period: time.Minute,
Key: func(ctx echo.Context) string {
return ctx.RealIP()
},
}
)
type (
Config struct {
Skipper middleware.Skipper
// Rediser
Rediser *redis.Client
// Max number of recent connections
// Default: 10
Max int
// Burst
Burst int
// StatusCode
// Default: 429 Too Many Requests
StatusCode int
// Message
// default: "Too many requests, please try again later."
Message string
// Algorithm
// Default: sliding window
Algorithm uint
// Prefix
// Default:
Prefix string
// SkipOnError
// Default: false
SkipOnError bool
// Period
Period time.Duration
// Key allows to use a custom handler to create custom keys
// Default: func(echo.Context) string {
// return ctx.RealIP()
// }
Key func(echo.Context) string
// Handler is called when a request hits the limit
// Default: func(c echo.Context) {
// return ctx.String(defaultStatusCode, defaultMessage)
// }
Handler func(echo.Context) error
// ErrHandler is called when a error happen inside go_limiiter lib
// Default: func(c echo.Context) {
// return ctx.String(defaultStatusCode, defaultMessage)
// }
ErrHandler func(error, echo.Context) error
}
)
func New(rediser *redis.Client) echo.MiddlewareFunc {
config := DefaultConfig
config.Rediser = rediser
return NewWithConfig(config)
}
func NewWithConfig(config Config) echo.MiddlewareFunc {
if config.Rediser == nil {
panic(errors.New("redis client is missing"))
}
if config.Skipper == nil {
config.Skipper = DefaultConfig.Skipper
}
if config.Max == 0 {
config.Max = DefaultConfig.Max
}
if config.Burst == 0 {
config.Burst = DefaultConfig.Burst
}
if config.StatusCode == 0 {
config.StatusCode = DefaultConfig.StatusCode
}
if config.Message == "" {
config.Message = DefaultConfig.Message
}
if config.Algorithm == 0 {
config.Algorithm = DefaultConfig.Algorithm
}
if config.Prefix == "" {
config.Prefix = DefaultConfig.Prefix
}
if config.Period == 0 {
config.Period = DefaultConfig.Period
}
if config.Key == nil {
config.Key = DefaultConfig.Key
}
if config.Handler == nil {
config.Handler = func(ctx echo.Context) error {
return ctx.String(config.StatusCode, config.Message)
}
}
if config.ErrHandler == nil {
config.ErrHandler = func(err error, ctx echo.Context) error {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
}
limiter := go_limiter.NewLimiter(config.Rediser)
limiter.Prefix = config.Prefix
limit := &go_limiter.Limit{
Period: config.Period,
Algorithm: config.Algorithm,
Rate: int64(config.Max),
Burst: int64(config.Burst),
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
if config.Skipper(ctx) {
return next(ctx)
}
result, err := limiter.Allow(config.Key(ctx), limit)
if err != nil {
ctx.Logger().Error(err)
if config.SkipOnError {
return next(ctx)
}
return config.ErrHandler(err, ctx)
}
res := ctx.Response()
// Check if hits exceed the max
if !result.Allowed {
// Return response with Retry-After header
// https://tools.ietf.org/html/rfc6584
res.Header().Set("Retry-After", strconv.FormatInt(time.Now().Add(result.RetryAfter).Unix(), 10))
// Call Handler func
return config.Handler(ctx)
}
// We can continue, update RateLimit headers
res.Header().Set("X-RateLimit-Limit", strconv.Itoa(config.Max))
res.Header().Set("X-RateLimit-Remaining", strconv.FormatInt(result.Remaining, 10))
res.Header().Set("X-RateLimit-Reset", strconv.FormatInt(time.Now().Add(result.ResetAfter).Unix(), 10))
return next(ctx)
}
}
}