middleware

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

README

HTTPServer Middleware 包

httpserver/middleware 提供可复用的 Gin 中间件,不依赖具体 metrics、tracing 或 auth 实现,适合作为 httpserver 的通用扩展层。

适用场景

  • 需要 panic recovery
  • 需要请求超时控制
  • 需要结构化访问日志和可选 payload 调试日志
  • 需要响应压缩
  • 需要单进程全局并发闸门,超限立即返回 503,不排队
  • 需要 Trace ID / Request ID 注入
  • 需要基础 CORS 与安全响应头
  • 需要限制请求体大小

快速开始

srv := httpserver.NewServer(nil)
srv.Use(middleware.AccessLog())
srv.Use(middleware.Compression())
srv.Use(middleware.Recovery())
srv.Use(middleware.ConcurrencyLimit(100))
srv.Use(middleware.Timeout(2 * time.Second))
srv.Use(middleware.TraceID())

ConcurrencyLimit

ConcurrencyLimit 用于控制单进程内的全局并发上限。当前请求数达到阈值时,新请求会直接返回 503 Service Unavailable,不会进入队列等待。

适合这些场景:

  • 防止单实例被突发流量打满
  • 保护下游数据库、RPC 或第三方接口
  • 希望用简单的闸门而不是排队来削峰

Timeout

Timeout 用于给单次请求链路注入协作式执行预算。它的职责是向 context.Context 传播 deadline,而不是强制终止正在运行的 goroutine。

这意味着:

  • handler、service、repository 和下游 client 需要协作感知 ctx.Done()
  • Timeout 不会主动杀掉 goroutine
  • TimeoutConcurrencyLimit 组合使用时,槽位释放以“请求真正执行结束”为准,而不是以“客户端已经收到 504”为准

适合这些场景:

  • 给入口请求设置统一执行预算
  • 让下游数据库、RPC 或 HTTP client 复用同一个 deadline
  • ConcurrencyLimit 配合时,明确“执行结束”才释放并发槽位

AccessLog

AccessLog 默认输出一条摘要访问日志,包含:

  • method
  • path
  • route
  • status
  • latency_ms
  • client_ip
  • request_id
  • trace_id
  • bytes_in
  • bytes_out

如果需要调试请求体和响应体,可以显式开启 payload capture:

srv.Use(middleware.AccessLog(middleware.AccessLogConfig{
    CapturePayload: true,
    MaxBodyBytes:   8 << 10,
    Multipart: middleware.MultipartConfig{
        Mode: middleware.MultipartFormFieldsOnly,
    },
}))

默认行为:

  • access log 始终输出摘要
  • payload log 默认关闭
  • JSON / form 会按字段脱敏
  • multipart 默认按结构化 part 处理,不记录文件内容

Compression

Compression 默认按 Accept-Encoding 协商响应压缩。第一版只支持 gzip,适合 JSON API、文本响应和较大的列表接口。

默认行为:

  • 不会自动挂载到 httpserver core
  • middleware 层需要显式启用
  • preset.NewProductionServer 中后续可作为推荐默认值
  • 小响应、SSE、下载和已压缩响应默认跳过

Documentation

Overview

Package middleware 提供可复用的 HTTP 中间件集合。

该包面向 `httpserver` 以及直接使用 Gin 的项目,提供 Recovery、Timeout、 TraceID、RequestID、AccessLog、Compression、ConcurrencyLimit、CORS、安全响应头和请求体大小限制等通用中间件。 其中 ConcurrencyLimit 用于单进程全局并发闸门,超限请求会立即返回 503,不排队等待。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccessLog

func AccessLog(configs ...AccessLogConfig) gin.HandlerFunc

AccessLog 记录结构化访问日志。

func CORS

func CORS(config CORSConfig) gin.HandlerFunc

CORS 返回跨域中间件。

func ClientIPFromRequest

func ClientIPFromRequest(r *http.Request) string

ClientIPFromRequest 从 http.Request 获取客户端 IP。 优先使用 RealIP 中间件设置的 context 值,降级到 RemoteAddr。

func Compression

func Compression(configs ...CompressionConfig) gin.HandlerFunc

Compression 在客户端声明支持 gzip 时压缩响应。

func ConcurrencyLimit

func ConcurrencyLimit(limit int) gin.HandlerFunc

ConcurrencyLimit 为单进程全局并发设置上限。

func ConcurrencyLimitWithConfig

func ConcurrencyLimitWithConfig(config ConcurrencyLimitConfig) gin.HandlerFunc

ConcurrencyLimitWithConfig 根据配置创建并发闸门中间件。

func MaxBodySize

func MaxBodySize(limit int64) gin.HandlerFunc

MaxBodySize 限制请求体大小。

func RateLimit

func RateLimit(rps float64) gin.HandlerFunc

RateLimit 创建全局速率限制中间件。

func RateLimitWithConfig

func RateLimitWithConfig(config RateLimitConfig) gin.HandlerFunc

RateLimitWithConfig 使用自定义配置创建速率限制中间件。

func RealIP

func RealIP() gin.HandlerFunc

RealIP 创建中间件(使用默认配置)。 默认配置下,不信任任何代理,直接使用 RemoteAddr。

func RealIPWithConfig

func RealIPWithConfig(config RealIPConfig) gin.HandlerFunc

RealIPWithConfig 使用自定义配置创建中间件。

func Recovery

func Recovery() gin.HandlerFunc

Recovery 在请求处理 panic 时返回 500。

func RecoveryWithConfig

func RecoveryWithConfig(config RecoveryConfig) gin.HandlerFunc

RecoveryWithConfig 使用自定义配置创建 Recovery 中间件。

func RequestID

func RequestID() gin.HandlerFunc

RequestID 为请求注入 request id。

func SecurityHeaders

func SecurityHeaders() gin.HandlerFunc

SecurityHeaders 添加基础安全响应头。

func SecurityHeadersWithConfig

func SecurityHeadersWithConfig(config SecurityHeadersConfig) gin.HandlerFunc

SecurityHeadersWithConfig 使用自定义配置创建安全头中间件。

func Timeout

func Timeout(timeout time.Duration) gin.HandlerFunc

Timeout 为请求设置处理超时。

func TimeoutWithConfig

func TimeoutWithConfig(config TimeoutConfig) gin.HandlerFunc

TimeoutWithConfig 使用自定义配置创建超时中间件。

func TraceID

func TraceID() gin.HandlerFunc

TraceID 为请求注入 trace id。

Types

type AccessLogConfig

type AccessLogConfig struct {
	Logger                 LoggerFunc
	CapturePayload         bool
	PayloadLogLevel        string
	MaxBodyBytes           int64
	AllowedContentTypes    []string
	AllowedRequestHeaders  []string
	AllowedResponseHeaders []string
	ShouldCapturePayload   func(*gin.Context, int) bool
	Multipart              MultipartConfig
	Redaction              RedactionConfig

	// SkipPaths 精确匹配路径跳过日志记录。
	// 示例: []string{"/health", "/readyz", "/livez"}
	SkipPaths []string

	// ShouldLog 完全自定义的日志过滤。
	// 返回 false 时跳过全部日志。
	ShouldLog func(*gin.Context) bool
}

AccessLogConfig 描述访问日志行为。

type CORSConfig

type CORSConfig struct {
	// AllowOrigins 允许的 Origin 列表。
	// 如果包含 "*",则允许所有 Origin(不可与 AllowCredentials 同时使用)。
	AllowOrigins []string

	// AllowOriginFunc 动态判断 Origin 是否允许。
	// 设置后完全接管 origin 判断,AllowOrigins 不再生效。
	// 返回 true 表示允许,返回 false 表示拒绝(不 fallback 到 AllowOrigins)。
	AllowOriginFunc func(origin string) bool

	AllowMethods  string
	AllowHeaders  string
	ExposeHeaders string

	// AllowCredentials 是否允许携带凭证。
	// 为 true 时不可使用 "*" 作为 AllowOrigin。
	AllowCredentials bool

	// MaxAge 预检请求缓存时间。
	MaxAge time.Duration
}

CORSConfig 描述跨域配置。

type CompressionConfig

type CompressionConfig struct {
	MinSizeBytes         int
	Level                int
	AllowedContentTypes  []string
	ExcludedContentTypes []string
	ShouldCompress       func(*gin.Context, int) bool
}

CompressionConfig 描述响应压缩行为。

type ConcurrencyLimitConfig

type ConcurrencyLimitConfig struct {
	Limit int
	// OnRejected 允许业务自定义限流拒绝响应;如果回调未写出响应,则回退到默认 503。
	OnRejected func(*gin.Context)
}

ConcurrencyLimitConfig 描述并发闸门配置。

type LoggerFunc

type LoggerFunc func(ctx context.Context, level string, event string, fields map[string]any)

LoggerFunc 抽象访问日志输出,避免 middleware 依赖具体日志实现。

type MultipartCaptureMode

type MultipartCaptureMode string

MultipartCaptureMode 控制 multipart payload 的捕获模式。

const (
	MultipartDisabled       MultipartCaptureMode = "disabled"
	MultipartMetadataOnly   MultipartCaptureMode = "metadata_only"
	MultipartFormFieldsOnly MultipartCaptureMode = "form_fields_only"
	MultipartSelectedParts  MultipartCaptureMode = "selected_parts"
)

type MultipartConfig

type MultipartConfig struct {
	Mode              MultipartCaptureMode
	PartAllowlist     []string
	MaxPartValueBytes int64
	RedactFilenames   bool
}

MultipartConfig 描述 multipart 载荷日志行为。

type RateLimitConfig

type RateLimitConfig struct {
	// Rate 每秒允许的请求数。
	Rate float64

	// Burst 突发上限,默认为 max(1, int(Rate))。
	Burst int

	// OnRejected 自定义拒绝响应。
	// 如果回调已写出响应,不再回退默认 429。
	OnRejected func(*gin.Context)
}

RateLimitConfig 描述速率限制行为。

type RealIPConfig

type RealIPConfig struct {
	// TrustedCIDRs 信任代理的 CIDR 列表。
	// 默认空列表,表示不信任任何代理(直接使用 RemoteAddr)。
	TrustedCIDRs []string

	// OnUntrusted 当检测到不可信代理时的处理函数。
	// 如果为 nil,则使用 RemoteAddr。
	OnUntrusted func(c *gin.Context, remoteAddr string)
}

RealIPConfig 配置可信代理解析。

type RecoveryConfig

type RecoveryConfig struct {
	// Logger 输出结构化恢复日志。
	// 复用 AccessLog 已有的 LoggerFunc 签名。
	Logger LoggerFunc

	// OnPanic 允许业务自定义 panic 后处理(如上报 Sentry)。
	// 在日志输出之后调用。
	OnPanic func(c *gin.Context, recovered any, stack []byte)
}

RecoveryConfig 描述 panic 恢复行为。

type RedactionConfig

type RedactionConfig struct {
	Rules         []RedactionRule
	MaxValueBytes int
	HashSalt      string
}

RedactionConfig 描述 payload 脱敏行为。

type RedactionRule

type RedactionRule struct {
	Scope    string
	Key      string
	Strategy RedactionStrategy
}

RedactionRule 描述一个 scope + key 的脱敏规则。

type RedactionStrategy

type RedactionStrategy string

RedactionStrategy 描述脱敏策略。

const (
	RedactionRedact RedactionStrategy = "redact"
	RedactionMask   RedactionStrategy = "mask"
	RedactionHash   RedactionStrategy = "hash"
	RedactionDrop   RedactionStrategy = "drop"
)

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	// HSTS 设置 Strict-Transport-Security 头。
	// 示例: "max-age=31536000; includeSubDomains"
	HSTS string

	// ContentSecurityPolicy 设置 Content-Security-Policy 头。
	// 示例: "default-src 'self'"
	ContentSecurityPolicy string

	// PermissionsPolicy 设置 Permissions-Policy 头。
	// 示例: "camera=(), microphone=()"
	PermissionsPolicy string
}

SecurityHeadersConfig 描述安全响应头行为。

type TimeoutConfig

type TimeoutConfig struct {
	// Timeout 请求处理超时时间。
	Timeout time.Duration

	// OnTimeout 自定义超时响应。
	// 如果回调未写出响应,回退到 504。
	OnTimeout func(*gin.Context)
}

TimeoutConfig 描述超时中间件行为。

Jump to

Keyboard shortcuts

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