refacor: improvement of rate limiting

This commit is contained in:
Jonas Kaninda
2024-11-24 15:59:47 +01:00
parent 3b2889e002
commit 6258b07c82
8 changed files with 57 additions and 30 deletions

View File

@@ -45,13 +45,17 @@ func (rl *TokenRateLimiter) RateLimitMiddleware() mux.MiddlewareFunc {
// RateLimitMiddleware limits request based on the number of requests peer minutes.
func (rl *RateLimiter) RateLimitMiddleware() mux.MiddlewareFunc {
window := time.Minute // requests per minute
if len(rl.unit) != 0 && rl.unit == "hour" {
window = time.Hour
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientIP := getRealIP(r)
clientID := fmt.Sprintf("%s-%s", rl.id, clientIP) // Generate client Id, ID+ route ID
logger.Debug("requests limiter: clientIP: %s, clientID: %s", clientIP, clientID)
if rl.redisBased {
err := redisRateLimiter(clientID, rl.requests)
err := redisRateLimiter(clientID, rl.unit, rl.requests)
if err != nil {
logger.Error("Redis Rate limiter error: %s", err.Error())
logger.Error("Too many requests from IP: %s %s %s", clientIP, r.URL, r.UserAgent())
@@ -64,7 +68,7 @@ func (rl *RateLimiter) RateLimitMiddleware() mux.MiddlewareFunc {
if !exists || time.Now().After(client.ExpiresAt) {
client = &Client{
RequestCount: 0,
ExpiresAt: time.Now().Add(rl.window),
ExpiresAt: time.Now().Add(window),
}
rl.clientMap[clientID] = client
}

View File

@@ -25,10 +25,13 @@ import (
)
// redisRateLimiter, handle rateLimit
func redisRateLimiter(clientIP string, rate int) error {
func redisRateLimiter(clientIP, unit string, rate int) error {
limit := redis_rate.PerMinute(rate)
if len(unit) != 0 && unit == "hour" {
limit = redis_rate.PerHour(rate)
}
ctx := context.Background()
res, err := limiter.Allow(ctx, clientIP, redis_rate.PerMinute(rate))
res, err := limiter.Allow(ctx, clientIP, limit)
if err != nil {
return err
}

View File

@@ -27,8 +27,8 @@ import (
// RateLimiter defines requests limit properties.
type RateLimiter struct {
requests int
unit string
id string
window time.Duration
clientMap map[string]*Client
mu sync.Mutex
origins []string
@@ -42,8 +42,8 @@ type Client struct {
}
type RateLimit struct {
Id string
Unit string
Requests int
Window time.Duration
Origins []string
Hosts []string
RedisBased bool
@@ -53,8 +53,8 @@ type RateLimit struct {
func (rateLimit RateLimit) NewRateLimiterWindow() *RateLimiter {
return &RateLimiter{
id: rateLimit.Id,
unit: rateLimit.Unit,
requests: rateLimit.Requests,
window: rateLimit.Window,
clientMap: make(map[string]*Client),
origins: rateLimit.Origins,
redisBased: rateLimit.RedisBased,