-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
45 lines (40 loc) · 962 Bytes
/
middleware.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
package main
import (
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"golang.org/x/time/rate"
)
type (
RateLimitConfig struct {
// Skipper defines a function to skip middleware.
Skipper middleware.Skipper
Limit int
Burst int
}
)
var DefaultRateLimitConfig = RateLimitConfig{
Skipper: middleware.DefaultSkipper,
Limit: 2,
Burst: 1,
}
func RateLimitMiddleware() echo.MiddlewareFunc {
return RateLimitWithConfig(DefaultRateLimitConfig)
}
func RateLimitWithConfig(config RateLimitConfig) echo.MiddlewareFunc {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultRateLimitConfig.Skipper
}
var limiter = rate.NewLimiter(rate.Limit(config.Limit), config.Burst)
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
if limiter.Allow() == false {
return echo.ErrTooManyRequests
}
return next(c)
}
}
}