-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #43 from Abbosbek-cloud/master
Feat: add rate limiter middleware to control API request rates
- Loading branch information
Showing
3 changed files
with
45 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package middleware | ||
|
||
import ( | ||
"net/http" | ||
"sync" | ||
"time" | ||
|
||
"github.com/labstack/echo/v4" | ||
"golang.org/x/time/rate" | ||
) | ||
|
||
func RateLimiter(maxRequests int, duration time.Duration) echo.MiddlewareFunc { | ||
// Create a map to hold rate limiters for each IP | ||
var visitors = make(map[string]*rate.Limiter) | ||
var mutex sync.Mutex | ||
|
||
return func(next echo.HandlerFunc) echo.HandlerFunc { | ||
return func(c echo.Context) error { | ||
ip := c.RealIP() | ||
|
||
// Lock the map to avoid race conditions | ||
mutex.Lock() | ||
if _, exists := visitors[ip]; !exists { | ||
visitors[ip] = rate.NewLimiter(rate.Every(duration), maxRequests) | ||
} | ||
|
||
limiter := visitors[ip] | ||
mutex.Unlock() | ||
|
||
if !limiter.Allow() { | ||
return c.JSON(http.StatusTooManyRequests, map[string]string{ | ||
"error": "Too many requests", | ||
}) | ||
} | ||
|
||
return next(c) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters