Skip to content

Commit

Permalink
adding rate limmiting headers
Browse files Browse the repository at this point in the history
  • Loading branch information
ayushsatyam146 committed Oct 2, 2024
1 parent 7894fd2 commit edf38dc
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions internal/middleware/ratelimiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ func RateLimiter(client *db.DiceDB, next http.Handler, limit, window int) http.H
// Check if the request count exceeds the limit
if requestCount >= limit {
slog.Warn("Request limit exceeded", "count", requestCount)
addRateLimitHeaders(w, limit, limit-(requestCount+1), requestCount+1, currentWindow+int64(window))
http.Error(w, "429 - Too Many Requests", http.StatusTooManyRequests)
return
}
Expand All @@ -77,6 +78,7 @@ func RateLimiter(client *db.DiceDB, next http.Handler, limit, window int) http.H
if _, err := client.Client.Incr(ctx, key).Result(); err != nil {
slog.Error("Error incrementing request count", "error", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
addRateLimitHeaders(w, limit, limit-(requestCount+1), requestCount+1, currentWindow+int64(window))
return
}

Expand All @@ -87,10 +89,20 @@ func RateLimiter(client *db.DiceDB, next http.Handler, limit, window int) http.H
}
}

// Add rate limit headers
addRateLimitHeaders(w, limit, limit-(requestCount+1), requestCount+1, currentWindow+int64(window))

// Log the successful request increment
slog.Info("Request processed", "count", requestCount+1)

// Call the next handler
next.ServeHTTP(w, r)
})
}

func addRateLimitHeaders(w http.ResponseWriter, limit, remaining, used int, resetTime int64) {
w.Header().Set("x-ratelimit-limit", strconv.Itoa(limit))
w.Header().Set("x-ratelimit-remaining", strconv.Itoa(remaining))
w.Header().Set("x-ratelimit-used", strconv.Itoa(used))
w.Header().Set("x-rateLimit-reset", strconv.FormatInt(resetTime, 10))
}

0 comments on commit edf38dc

Please sign in to comment.