Skip to content

Commit

Permalink
Merge pull request #43 from Abbosbek-cloud/master
Browse files Browse the repository at this point in the history
Feat: add rate limiter middleware to control API request rates
  • Loading branch information
Firdavs9512 authored Nov 1, 2024
2 parents 64cbd48 + 1ab0bfa commit b7a9893
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ require (
golang.org/x/sys v0.25.0
gorm.io/gorm v1.25.12
k8s.io/apimachinery v0.31.1
golang.org/x/time v0.6.0
)

require (
Expand Down Expand Up @@ -85,7 +86,6 @@ require (
golang.org/x/net v0.29.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/text v0.18.0 // indirect
golang.org/x/time v0.6.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
Expand Down
39 changes: 39 additions & 0 deletions internal/middleware/rate_limiter.go
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)
}
}
}
5 changes: 5 additions & 0 deletions internal/router/router_base.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package router

import (
"time"

"github.com/labstack/echo/v4"
apiV1 "github.com/sail-host/cloud/internal/app/api/v1"
"github.com/sail-host/cloud/internal/middleware"
Expand All @@ -11,6 +13,9 @@ type BaseRouter struct {

func (r *BaseRouter) InitRouter(Router *echo.Group) {
baseRouter := Router.Group("/auth")

baseRouter.Use(middleware.RateLimiter(5, 30*time.Second)) // 5 requests per 30 seconds

baseApi := apiV1.ApiGroupApp.BaseApi
{
baseRouter.POST("/login", baseApi.Login)
Expand Down

0 comments on commit b7a9893

Please sign in to comment.