做完了一部分,备份一下,防止以外删除

This commit is contained in:
2025-11-11 15:16:38 +08:00
parent 9600e5b6e0
commit e98dd4d725
39 changed files with 2423 additions and 183 deletions

View File

@@ -0,0 +1,41 @@
package middleware
import (
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/limiter"
"github.com/gofiber/storage/redis/v3"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
"github.com/break/junhong_cmp_fiber/pkg/response"
)
// RateLimiter 创建基于 IP 的限流中间件
// storage 参数nil = 内存存储,传入 Redis storage = 分布式限流
func RateLimiter(max int, expiration time.Duration, storage fiber.Storage) fiber.Handler {
return limiter.New(limiter.Config{
Max: max,
Expiration: expiration,
KeyGenerator: func(c *fiber.Ctx) string {
// 使用统一的 Redis 键生成函数
return constants.RedisRateLimitKey(c.IP())
},
LimitReached: func(c *fiber.Ctx) error {
return response.Error(c, 400, errors.CodeTooManyRequests, errors.GetMessage(errors.CodeTooManyRequests, "zh"))
},
Storage: storage, // 支持内存或 Redis 存储
})
}
// NewRedisStorage 创建 Redis 存储用于限流
func NewRedisStorage(addr, password string, db, prot int) fiber.Storage {
return redis.New(redis.Config{
Host: addr,
Port: prot,
Password: password,
Database: db,
Reset: false,
})
}