mirror of
https://github.com/wgh136/nysoure.git
synced 2025-09-27 04:17:23 +00:00
Move request limiter to middleware.
This commit is contained in:
34
server/middleware/request_limiter.go
Normal file
34
server/middleware/request_limiter.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"nysoure/server/utils"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/log"
|
||||
)
|
||||
|
||||
func NewRequestLimiter(maxRequests int, duration time.Duration) func(c fiber.Ctx) error {
|
||||
limiter := utils.NewRequestLimiter(func() int {
|
||||
return maxRequests
|
||||
}, duration)
|
||||
|
||||
return func(c fiber.Ctx) error {
|
||||
if !limiter.AllowRequest(c.IP()) {
|
||||
log.Warnf("IP %s has exceeded the request limit of %d requests in %s", c.IP(), maxRequests, duration)
|
||||
return fiber.NewError(fiber.StatusTooManyRequests, "Too many requests")
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func NewDynamicRequestLimiter(maxRequestsFunc func() int, duration time.Duration) func(c fiber.Ctx) error {
|
||||
limiter := utils.NewRequestLimiter(maxRequestsFunc, duration)
|
||||
|
||||
return func(c fiber.Ctx) error {
|
||||
if !limiter.AllowRequest(c.IP()) {
|
||||
return fiber.NewError(fiber.StatusTooManyRequests, "Too many requests")
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user