middleware

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package middleware 提供 ginx 的内置中间件集合, 每个中间件独立一个文件; 各中间件均可脱离 ginx, 直接用于原生 gin。

当前提供:

  • TraceID: 链路追踪中间件, 读取/生成 trace id 并注入 context 与响应头; SetTraceID 供 trace 包(OpenTelemetry)等外部追踪实现桥接同一套约定(见 traceid.go)
  • Binding: 泛型参数绑定工厂, 校验失败自动统一 400 响应(见 binding.go)
  • Telemetry: 可观测端点(Prometheus 指标 + pprof 剖析)与指标采集中间件, 指标名前缀(Namespace)与直方图分桶(Buckets)可配(见 telemetry.go)
  • CORS: 跨域资源共享中间件(见 cors.go)
  • RateLimit: 固定窗口限流中间件(见 ratelimit.go)

使用示例:

// 方式一: 经 ginx 配置启用, 对应配置节点非 nil 时自动注入
r := &ginx.Gin{
	TraceID:   &middleware.TraceID{},
	Telemetry: &middleware.Telemetry{Metrics: true, Pprof: true},
	CORS:      &middleware.CORS{AllowOrigins: []string{"https://example.com"}},
	RateLimit: &middleware.RateLimit{Limit: 100, Window: time.Second},
}

// 方式二: 脱离 ginx, 直接用于原生 gin(绑定工厂直接挂在路由上)
e := gin.New()
h, _ := (&middleware.CORS{AllowOrigins: []string{"https://example.com"}}).Handler()
e.Use(h)
e.POST("/users", middleware.Bind(handleCreate))

Index

Constants

View Source
const (
	DefaultMetricsPath = "/metrics"     // Prometheus 抓取端点
	DefaultPprofPrefix = "/debug/pprof" // pprof 剖析端点前缀
)

可观测端点默认路径

View Source
const (
	// DefaultTraceHeader 默认读取/回写的请求头
	DefaultTraceHeader = "X-Request-Id"
)

trace id 默认约定

Variables

This section is empty.

Functions

func Bind added in v1.0.4

func Bind[T any](fn func(c *gin.Context, req *T)) gin.HandlerFunc

Bind 泛型绑定 handler 工厂: 依据 Content-Type 将请求参数绑定到 T 并校验, 失败时按统一格式写入 400 响应(与 errcode.ErrInvalidParams 联动); 成功时以绑定结果调用 fn。原生 gin 项目也可直接使用:

r.POST("/users", middleware.Bind(handleCreate))
func handleCreate(c *gin.Context, req *CreateUserReq) { ... }

func BindJSON added in v1.0.4

func BindJSON[T any](fn func(c *gin.Context, req *T)) gin.HandlerFunc

BindJSON 泛型绑定 JSON 请求体, 见 Bind。

func BindQuery added in v1.0.4

func BindQuery[T any](fn func(c *gin.Context, req *T)) gin.HandlerFunc

BindQuery 泛型绑定 URL 查询参数(form 标签), 见 Bind。

func BindURI added in v1.0.4

func BindURI[T any](fn func(c *gin.Context, req *T)) gin.HandlerFunc

BindURI 泛型绑定路径参数(uri 标签), 见 Bind。

func ExtractValidationError added in v1.0.4

func ExtractValidationError(err error) string

ExtractValidationError 提取校验错误信息: validator 的校验错误转为 "字段 规则[=参数]" 列表(如 "Username required; Age min=18"), 其他错误原样返回。ginx.Bind 系列与 middleware.Bind 系列共用本约定。

func SetTraceID added in v1.0.4

func SetTraceID(c *gin.Context, id string)

SetTraceID 注入 trace id 到当前请求, 供 trace 包等外部追踪实现桥接: 写入后 TraceIDOf / TraceIDField 无感知生效, 日志聚合与响应头约定保持不变。

func SetValidationErrorExtractor added in v1.0.4

func SetValidationErrorExtractor(fn func(error) string)

SetValidationErrorExtractor 替换校验错误信息提取器(如对接 i18n)。 提取器接收 ShouldBind 返回的原始错误, 返回展示给客户端的信息。

func TraceIDField added in v1.0.4

func TraceIDField(c *gin.Context) zap.Field

TraceIDField 返回携带 trace_id 的结构化日志字段, 配合 logger 使用:

logger.Info("create order", middleware.TraceIDField(c))

func TraceIDOf added in v1.0.4

func TraceIDOf(c *gin.Context) string

TraceIDOf 读取当前请求的 trace id(经 TraceID 中间件注入), 未启用中间件时返回空串。

Types

type CORS

type CORS struct {
	AllowOrigins     []string      `yaml:"allow_origins" toml:"allow_origins" json:"allow_origins" mapstructure:"allow_origins"`                 // 允许的源(协议+域名+端口), "*" 匹配全部(默认 *)
	AllowMethods     []string      `yaml:"allow_methods" toml:"allow_methods" json:"allow_methods" mapstructure:"allow_methods"`                 // 允许的方法, 默认 GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS
	AllowHeaders     []string      `yaml:"allow_headers" toml:"allow_headers" json:"allow_headers" mapstructure:"allow_headers"`                 // 允许的请求头, 默认 Origin/Content-Type/Accept/Authorization/X-Requested-With
	ExposeHeaders    []string      `yaml:"expose_headers" toml:"expose_headers" json:"expose_headers" mapstructure:"expose_headers"`             // 允许前端读取的响应头(可选)
	AllowCredentials bool          `yaml:"allow_credentials" toml:"allow_credentials" json:"allow_credentials" mapstructure:"allow_credentials"` // 允许携带凭证(Cookie), 不可与 "*" 源同时使用
	MaxAge           time.Duration `yaml:"max_age" toml:"max_age" json:"max_age" mapstructure:"max_age"`                                         // 预检结果缓存时长(<=0 时默认 12h)
}

CORS 跨域资源共享配置, 由 ginx.Gin.CORS 设置后启用内置跨域中间件; 未设置的字段自动使用默认值。也可脱离 ginx, 经 Handler 直接用于原生 gin。

func (*CORS) Handler

func (c *CORS) Handler() (gin.HandlerFunc, error)

Handler 构建跨域中间件: 未设置的字段自动填充默认值, 配置不合法时返回错误。 ginx 在 Gin.CORS 非 nil 时自动注入; 也可在原生 gin 中直接 e.Use 使用。

type RateLimit

type RateLimit struct {
	Limit  int           `yaml:"limit" toml:"limit" json:"limit" mapstructure:"limit"`     // 单个客户端每个窗口内允许的最大请求数(<=0 时默认 100)
	Window time.Duration `yaml:"window" toml:"window" json:"window" mapstructure:"window"` // 统计时间窗口(<=0 时默认 1s)

	// KeyFunc 限流键生成函数, 返回相同键的请求共享同一配额;
	// 默认取客户端 IP, 需按用户 ID / API Key 限流时注入; 仅支持代码注入
	KeyFunc func(c *gin.Context) string `yaml:"-" toml:"-" json:"-" mapstructure:"-"`
}

RateLimit 固定窗口限流配置, 由 ginx.Gin.RateLimit 设置后启用内置限流中间件; 未设置的字段自动使用默认值。也可脱离 ginx, 经 Handler 直接用于原生 gin。

func (*RateLimit) Handler

func (r *RateLimit) Handler() (gin.HandlerFunc, error)

Handler 构建限流中间件: 未设置的字段自动填充默认值。 以固定窗口统计各键的请求次数, 超限返回 429 与 Retry-After; ginx 在 Gin.RateLimit 非 nil 时自动注入, 也可在原生 gin 中直接 e.Use 使用。

type Telemetry added in v1.0.4

type Telemetry struct {
	// Metrics 是否开启 Prometheus 指标: 注入采集中间件并挂载抓取端点
	Metrics bool `yaml:"metrics" toml:"metrics" json:"metrics" mapstructure:"metrics"`
	// MetricsPath 指标抓取端点路径(默认 /metrics)
	MetricsPath string `yaml:"metrics_path" toml:"metrics_path" json:"metrics_path" mapstructure:"metrics_path"`

	// Pprof 是否开启 pprof 剖析端点(heap/goroutine/mutex/cpu 等);
	// 生产环境建议置于内网或叠加鉴权中间件, 避免暴露运行时细节
	Pprof bool `yaml:"pprof" toml:"pprof" json:"pprof" mapstructure:"pprof"`
	// PprofPrefix pprof 端点前缀(默认 /debug/pprof)
	PprofPrefix string `yaml:"pprof_prefix" toml:"pprof_prefix" json:"pprof_prefix" mapstructure:"pprof_prefix"`

	// Namespace 指标名前缀(默认空); 多服务共用 Prometheus 时设置为服务名,
	// 指标变为 <namespace>_http_request_duration_seconds 便于按服务聚合。
	// 多 Telemetry 实例并存时以首个启用者的配置为准
	Namespace string `yaml:"namespace" toml:"namespace" json:"namespace" mapstructure:"namespace"`
	// Buckets 耗时直方图分桶边界(秒, 默认 prometheus.DefBuckets);
	// 按业务时延分布定制, 示例: [0.005, 0.01, 0.05, 0.1, 0.5, 1, 5]。
	// 多 Telemetry 实例并存时以首个启用者的配置为准
	Buckets []float64 `yaml:"buckets" toml:"buckets" json:"buckets" mapstructure:"buckets"`
}

Telemetry 可观测性端点配置, 由 ginx.Gin.Telemetry 设置后启用; Metrics 开启时注入指标采集中间件并挂载抓取端点, Pprof 开启时挂载剖析端点。 也可脱离 ginx, 在原生 gin 中经 Handler/Mount 自行接入。

func (*Telemetry) Handler added in v1.0.4

func (t *Telemetry) Handler() (gin.HandlerFunc, error)

Handler 构建指标采集中间件: 记录每请求的耗时与总数, 标签为 method / 路由模板 path / status。仅 Metrics 开启时由 ginx 注入; 脱离 ginx 直接调用时按本实例配置注册指标(首个配置生效)。

func (*Telemetry) Mount added in v1.0.4

func (t *Telemetry) Mount(e *gin.Engine) error

Mount 在引擎上挂载已开启的可观测端点, 由 ginx.Build 调用; 路径与业务路由冲突时返回错误而非 panic。

type TraceID added in v1.0.4

type TraceID struct {
	// Header 读取与回写 trace id 的请求头(默认 X-Request-Id)
	Header string `yaml:"header" toml:"header" json:"header" mapstructure:"header"`

	// Generator trace id 生成函数, 上游未携带时使用:
	// 默认 crypto/rand 16 字节 hex(32 位小写); 需对接既有追踪体系
	// (如 uuid / OpenTelemetry TraceID)时注入; 仅支持代码注入
	Generator func() string `yaml:"-" toml:"-" json:"-" mapstructure:"-"`
}

TraceID 链路追踪配置, 由 ginx.Gin.TraceID 设置后启用内置追踪中间件; 也可脱离 ginx, 经 Handler 直接用于原生 gin。

func (*TraceID) Handler added in v1.0.4

func (t *TraceID) Handler() (gin.HandlerFunc, error)

Handler 构建追踪中间件: 优先读取上游请求头携带的 trace id, 缺失时经 Generator 生成; 注入 gin context(TraceIDOf 读取)并 写入响应头回传客户端, 使同一请求的日志可按 trace_id 聚合。

Jump to

Keyboard shortcuts

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