Skip to content

Instantly share code, notes, and snippets.

@maiacodes
Created January 19, 2021 12:50
Show Gist options
  • Select an option

  • Save maiacodes/69bafbbb4339feb3dc29772b89953d9f to your computer and use it in GitHub Desktop.

Select an option

Save maiacodes/69bafbbb4339feb3dc29772b89953d9f to your computer and use it in GitHub Desktop.
Post Requests Rate-Limiter (Golang & Echo)
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