Skip to content

Commit

Permalink
refactor redisratelimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
zetaab committed Dec 9, 2023
1 parent 38ea4f6 commit d56d636
Showing 1 changed file with 21 additions and 20 deletions.
41 changes: 21 additions & 20 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,29 @@ func RedisRateLimiter(rdb *redis.Client, key KeyFunc, errFunc ErrFunc) gin.Handl
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
}
if limit == nil || rdb == nil {
c.Next()
return
}
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()
}
}

0 comments on commit d56d636

Please sign in to comment.