Created
January 19, 2021 12:50
-
-
Save maiacodes/69bafbbb4339feb3dc29772b89953d9f to your computer and use it in GitHub Desktop.
Post Requests Rate-Limiter (Golang & Echo)
This file contains hidden or 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
| package rate_limiter | |
| import ( | |
| "github.com/labstack/echo/v4" | |
| "golang.org/x/time/rate" | |
| "net/http" | |
| "time" | |
| ) | |
| var ( | |
| ipLimits = make(map[string]*rate.Limiter) | |
| ) | |
| func Middleware() echo.MiddlewareFunc { | |
| var globalLimiter = rate.NewLimiter(rate.Every(10*time.Minute), 100) | |
| return func(next echo.HandlerFunc) echo.HandlerFunc { | |
| return func(c echo.Context) error { | |
| if c.Request().Method != "POST" { | |
| return next(c) | |
| } | |
| limiter, ok := ipLimits[c.RealIP()] | |
| if !ok { | |
| ipLimits[c.RealIP()] = rate.NewLimiter(rate.Every(10*time.Minute), 10) | |
| } else { | |
| if !limiter.Allow() { | |
| return echo.ErrTooManyRequests | |
| } | |
| } | |
| if globalLimiter.Allow() == false { | |
| return echo.NewHTTPError(http.StatusTooManyRequests, "The service is overwhelmed! Please try again later.") | |
| } | |
| return next(c) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment