Skip to content

Commit

Permalink
fix: add limiter middleware feature
Browse files Browse the repository at this point in the history
  • Loading branch information
OldSmokeGun committed Oct 9, 2023
1 parent 7de26a1 commit d6d1c42
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
51 changes: 51 additions & 0 deletions internal/app/adapter/server/http/middleware/limit.go
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)
}
}
}
2 changes: 2 additions & 0 deletions internal/app/adapter/server/http/router/api_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
echoSwagger "github.com/swaggo/echo-swagger"

"go-scaffold/internal/app/adapter/server/http/api/docs"
imiddleware "go-scaffold/internal/app/adapter/server/http/middleware"
"go-scaffold/internal/config"
)

Expand Down Expand Up @@ -47,6 +48,7 @@ func (g *ApiGroup) setup(prefix string, rg *echo.Group) {
func (g *ApiGroup) useMiddlewares() {
// allowed to cross
g.group.Use(middleware.CORS())
g.group.Use(imiddleware.Limit(*imiddleware.NewDefaultLimitConfig()))
}

func (g *ApiGroup) useRoutes(e *echo.Echo) {
Expand Down

0 comments on commit d6d1c42

Please sign in to comment.