Some checks failed
CI/CD Pipeline / Test (push) Failing after 22m19s
CI/CD Pipeline / Security Scan (push) Failing after 5m57s
CI/CD Pipeline / Build (amd64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (amd64, linux) (push) Has been skipped
CI/CD Pipeline / Build (amd64, windows) (push) Has been skipped
CI/CD Pipeline / Build (arm64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (arm64, linux) (push) Has been skipped
CI/CD Pipeline / Build Docker Image (push) Has been skipped
CI/CD Pipeline / Create Release (push) Has been skipped
27 lines
734 B
Go
27 lines
734 B
Go
package middleware
|
||
|
||
import (
|
||
"time"
|
||
|
||
"github.com/gofiber/fiber/v2"
|
||
"github.com/gofiber/fiber/v2/middleware/limiter"
|
||
)
|
||
|
||
// SetupRateLimit 设置限流中间件
|
||
// 防止API滥用,限制每个IP的请求频率
|
||
func SetupRateLimit(maxRequests int, expiration int) fiber.Handler {
|
||
return limiter.New(limiter.Config{
|
||
Max: maxRequests,
|
||
Expiration: time.Duration(expiration) * time.Second, // 过期时间(秒)
|
||
KeyGenerator: func(c *fiber.Ctx) string {
|
||
return c.IP()
|
||
},
|
||
LimitReached: func(c *fiber.Ctx) error {
|
||
return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{
|
||
"success": false,
|
||
"error": "Rate limit exceeded",
|
||
"message": "Too many requests, please try again later",
|
||
})
|
||
},
|
||
})
|
||
} |