mirror of
https://github.com/wgh136/nysoure.git
synced 2025-09-27 12:17:24 +00:00
35 lines
930 B
Go
35 lines
930 B
Go
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()
|
|
}
|
|
}
|