Files
junhong_cmp_fiber/internal/middleware/ratelimit.go
huang d66323487b refactor: align framework cleanup with new bootstrap flow
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-11-19 12:47:25 +08:00

41 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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"
)
// 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 errors.New(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,
})
}