web_middleware

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 23, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CorsMiddleware

func CorsMiddleware() gin.HandlerFunc

CorsMiddleware 跨域中间件

func GinLogger

func GinLogger(skipPaths []string, skipKeywords []string) gin.HandlerFunc

GinLogger gin 日志请求中间件 skipPaths: 需要跳过的完全匹配路径列表 skipKeywords: 需要跳过的包含关键字列表

func IPFilterMiddleware

func IPFilterMiddleware(maxRequestsPerIP int, timeWindow time.Duration) gin.HandlerFunc

IPFilterMiddleware 中间件用于过滤IP并限制请求频率 maxRequestsPerIP ip请求阈值 example:200 timeWindow 统计时间 example: 1*time.Minute

func IPFilterWithRedisMiddleware

func IPFilterWithRedisMiddleware(redisClient *redis.Client, maxRequestsPerIP int, timeWindow time.Duration, customMsg ...string) gin.HandlerFunc

IPFilterWithRedisMiddleware 是一个基于 Redis 的滑动窗口限流中间件。 实现原理:

  • 每次请求时,将当前毫秒时间戳作为 score 和 member 添加到 Redis 的 ZSET(有序集合)中。
  • 先移除 ZSET 中窗口外(即当前时间减去 timeWindow 之前)的所有请求记录。
  • 统计 ZSET 当前元素数量,即为当前时间窗口内的请求数。
  • 若请求数超过 maxRequestsPerIP,则拒绝请求,否则允许通过。
  • 所有 Redis 操作通过 Lua 脚本一次性原子完成,提升性能和一致性。
  • 支持自定义超限响应消息,并在响应头中返回剩余可用请求数(X-RateLimit-Remaining)。

参数说明:

redisClient      Redis 客户端实例,用于存储和操作限流数据。
maxRequestsPerIP 单个 IP 在 timeWindow 时间窗口内允许的最大请求数。
timeWindow       滑动时间窗口长度,例如 1 秒、1 分钟等。
customMsg        (可选)自定义超限时的响应消息,未传递则使用默认提示。

func RequestIDMiddleware

func RequestIDMiddleware() gin.HandlerFunc

RequestIDMiddleware requestID请求中间件

func TimeoutMiddleware

func TimeoutMiddleware(reqTimeout time.Duration) gin.HandlerFunc

TimeoutMiddleware 接口超时中间件

func TimeoutResponse

func TimeoutResponse(c *gin.Context)

TimeoutResponse 超时响应

Types

type IPCounter

type IPCounter struct {
	Count      int       // Count ip计数
	LastAccess time.Time // LastAccess 请求时间
}

IPCounter 用于记录IP请求计数和时间

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL