refactor: refactoring of rate limiting

This commit is contained in:
Jonas Kaninda
2024-11-24 23:09:13 +01:00
parent 3df8dce59b
commit f4e5bb3be2
3 changed files with 60 additions and 29 deletions

View File

@@ -53,13 +53,11 @@ func (rl *RateLimiter) RateLimitMiddleware() mux.MiddlewareFunc {
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.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())
RespondWithError(w, http.StatusTooManyRequests, fmt.Sprintf("%d Too many requests, API requests limit exceeded. Please try again later", http.StatusTooManyRequests))
return
}
} else {
@@ -82,8 +80,10 @@ func (rl *RateLimiter) RateLimitMiddleware() mux.MiddlewareFunc {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
}
RespondWithError(w, http.StatusTooManyRequests, fmt.Sprintf("%d Too many requests, API requests limit exceeded. Please try again later", http.StatusTooManyRequests))
return
}
}
// Proceed to the next handler if the request limit is not exceeded
next.ServeHTTP(w, r)
})

View File

@@ -33,6 +33,8 @@ type RateLimiter struct {
mu sync.Mutex
origins []string
redisBased bool
pathBased bool
paths []string
}
// Client stores request count and window expiration for each client.
@@ -47,6 +49,8 @@ type RateLimit struct {
Origins []string
Hosts []string
RedisBased bool
PathBased bool
Paths []string
}
// NewRateLimiterWindow creates a new RateLimiter.
@@ -58,6 +62,8 @@ func (rateLimit RateLimit) NewRateLimiterWindow() *RateLimiter {
clientMap: make(map[string]*Client),
origins: rateLimit.Origins,
redisBased: rateLimit.RedisBased,
pathBased: rateLimit.PathBased,
paths: rateLimit.Paths,
}
}