-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathratelimit.go
59 lines (53 loc) · 1.41 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
package common
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"github.com/go-redis/redis_rate/v9"
)
type (
KeyFunc func(*gin.Context) (key string, limit *int, err error)
ErrFunc func(*gin.Context, error) (shouldReturn bool)
)
const (
ratelimitReset = "X-Ratelimit-Reset"
ratelimitLimit = "X-Ratelimit-Limit"
ratelimitRemaining = "X-Ratelimit-Remaining"
)
// RedisRateLimiter ...
func RedisRateLimiter(rdb *redis.Client, key KeyFunc, errFunc ErrFunc) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
limiter := redis_rate.NewLimiter(rdb)
key, limit, err := key(c)
if err != nil {
c.JSON(400, ErrorResponse{Code: 400, Message: err.Error()})
c.Abort()
return
}
if limit != nil && rdb != nil {
res, err := limiter.Allow(ctx, key, redis_rate.PerMinute(PtrValue(limit)))
if err == nil {
reset := time.Now().Add(res.ResetAfter)
c.Header(ratelimitReset, strconv.Itoa(int(reset.Unix())))
c.Header(ratelimitLimit, strconv.Itoa(PtrValue(limit)))
c.Header(ratelimitRemaining, strconv.Itoa(res.Remaining))
if res.Allowed <= 0 {
c.JSON(http.StatusTooManyRequests,
ErrorResponse{Code: http.StatusTooManyRequests, Message: "rate limit exceeded"},
)
c.Abort()
return
}
} else {
shouldReturn := errFunc(c, err)
if shouldReturn {
return
}
}
}
c.Next()
}
}