-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7de26a1
commit d6d1c42
Showing
2 changed files
with
53 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package middleware | ||
|
||
import ( | ||
"net/http" | ||
"time" | ||
|
||
"github.com/labstack/echo/v4" | ||
"github.com/labstack/echo/v4/middleware" | ||
"golang.org/x/time/rate" | ||
) | ||
|
||
type LimitConfig struct { | ||
// Skipper defines a function to skip middleware. | ||
Skipper middleware.Skipper | ||
|
||
// Limiter handle the limit of request | ||
Limiter *rate.Limiter | ||
} | ||
|
||
func (c *LimitConfig) WithSkipper(skipper middleware.Skipper) *LimitConfig { | ||
c.Skipper = skipper | ||
return c | ||
} | ||
|
||
func (c *LimitConfig) WithLimiter(limiter *rate.Limiter) *LimitConfig { | ||
c.Limiter = limiter | ||
return c | ||
} | ||
|
||
func NewDefaultLimitConfig() *LimitConfig { | ||
return &LimitConfig{ | ||
Skipper: middleware.DefaultSkipper, | ||
Limiter: rate.NewLimiter(rate.Every(time.Second/10), 60), | ||
} | ||
} | ||
|
||
func Limit(config LimitConfig) echo.MiddlewareFunc { | ||
return func(next echo.HandlerFunc) echo.HandlerFunc { | ||
return func(c echo.Context) error { | ||
if config.Skipper(c) { | ||
return next(c) | ||
} | ||
|
||
if !config.Limiter.Allow() { | ||
return echo.NewHTTPError(http.StatusTooManyRequests, "requests are too frequent") | ||
} | ||
|
||
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