middleware

package
v2.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package middleware 提供 webx 内置的 HTTP 中间件实现。 包含 Recovery、RequestID、Timeout、CORS、Validation、RateLimit 与 AccessLog。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccessLog

func AccessLog(logger logx.Logger, opts AccessLogOptions) core.HandlerFunc

AccessLog 返回访问日志中间件。

func BodyLimit

func BodyLimit(maxBytes int64) core.HandlerFunc

BodyLimit 返回请求体大小限制中间件(默认文案)。 Content-Length 明确超限时直接返回 413;chunked 请求体由 MaxBytesReader 兜底。

func BodyLimitWithOptions

func BodyLimitWithOptions(maxBytes int64, opts BodyLimitOptions) core.HandlerFunc

BodyLimitWithOptions 返回带文案选项的请求体大小限制中间件。 Content-Length 明确超限时直接返回 413;chunked 请求体由 MaxBytesReader 兜底。

func CORS

func CORS(cfg CORSConfig) core.HandlerFunc

CORS 返回 CORS 跨域处理中间件。

func ConcurrencyLimit

func ConcurrencyLimit(l *ConcurrencyLimiter) core.HandlerFunc

ConcurrencyLimit 返回并发限制中间件;额度已满时返回 503 并携带 Retry-After。

func Gzip

func Gzip() core.HandlerFunc

Gzip 返回响应压缩中间件:客户端 Accept-Encoding 含 gzip 时启用。

func GzipWithOptions

func GzipWithOptions(opts GzipOptions) core.HandlerFunc

GzipWithOptions 返回带选项的响应压缩中间件。

func Hooks

func Hooks(onRequest, onResponse func(*core.Context)) core.HandlerFunc

Hooks 返回请求钩子中间件:进入时调用 onRequest,处理结束后调用 onResponse。 可用于 OpenTelemetry 适配等观测场景;回调可传 nil。

func MetricsHandler

func MetricsHandler(m *Metrics) core.HandlerFunc

MetricsHandler 返回指标采集中间件。 panic 安全:请求处理发生 panic 时仍会记录请求数、耗时与 5xx 分布, 随后重新抛出 panic 交由 Recovery 中间件处理。

func RateLimit

func RateLimit(rl *RateLimiter) core.HandlerFunc

RateLimit 返回 IP 令牌桶限流中间件,超限返回标准化 429。

func Recovery

func Recovery() core.HandlerFunc

Recovery 返回 Panic 捕获中间件,这是组件库中唯一调用 recover() 的位置。

func RecoveryWith

func RecoveryWith(logger logx.Logger, m *Metrics) core.HandlerFunc

RecoveryWith 返回 Panic 捕获中间件,统计 panic 数量并输出日志。

func RecoveryWithMetrics

func RecoveryWithMetrics(m *Metrics) core.HandlerFunc

RecoveryWithMetrics 返回 Panic 捕获中间件,并统计 panic 数量。

func RecoveryWithOptions

func RecoveryWithOptions(logger logx.Logger, m *Metrics, debugMode bool) core.HandlerFunc

RecoveryWithOptions 返回 Panic 捕获中间件;debugMode 为 true 时响应携带 panic 摘要。

func RequestID

func RequestID() core.HandlerFunc

RequestID 返回请求 ID 生成中间件。 优先使用请求头 X-Request-ID,否则生成 UUID v7。

func RequestIDWithOptions

func RequestIDWithOptions(opts RequestIDOptions) core.HandlerFunc

RequestIDWithOptions 返回按选项配置的请求 ID 生成中间件。

func SecurityHeaders

func SecurityHeaders(opts SecurityHeadersOptions) core.HandlerFunc

SecurityHeaders 返回安全响应头中间件。

func Timeout

func Timeout(timeout time.Duration) core.HandlerFunc

Timeout 返回请求超时中间件(默认文案)。 向请求注入带超时的 Context;超时后丢弃 Handler 写入并返回 503。

func TimeoutWithOptions

func TimeoutWithOptions(timeout time.Duration, opts TimeoutOptions) core.HandlerFunc

TimeoutWithOptions 返回带文案选项的请求超时中间件。

func Validation

func Validation() core.HandlerFunc

Validation 返回请求参数校验中间件: 校验 Content-Type 是否为 JSON、Content-Length 是否超过 10MB。

Types

type AccessLogOptions

type AccessLogOptions struct {
	// LogSuccess 是否记录成功请求(默认仅记录非 2xx)。
	LogSuccess bool
	// SampleRate 采样率:0 表示记录全部;N>0 表示平均每 N 条记录 1 条。
	SampleRate int
	// RedactKeys query 参数中需要脱敏的键。
	RedactKeys []string
	// SlowThreshold 慢请求阈值;>0 且请求耗时达到阈值时额外记录 Warn(默认关闭)。
	SlowThreshold time.Duration
	// HeaderKeys 需要写入日志的请求头白名单(命中 RedactKeys 的值会脱敏)。
	HeaderKeys []string
}

AccessLogOptions 定义访问日志中间件的配置。

type BodyLimitOptions

type BodyLimitOptions struct {
	// Message 超限响应文案(默认 "请求体过大")。
	Message string
}

BodyLimitOptions 定义请求体限制中间件的配置。

type CORSConfig

type CORSConfig struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	ExposeHeaders    []string
	MaxAge           int
	AllowCredentials bool
	// AllowPrivateNetwork 预检响应输出 Access-Control-Allow-Private-Network: true。
	AllowPrivateNetwork bool
}

CORSConfig 定义 CORS 中间件的配置参数。

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig 返回常用 CORS 默认配置。

type ConcurrencyLimiter

type ConcurrencyLimiter struct {
	// contains filtered or unexported fields
}

ConcurrencyLimiter 限制同一时刻处理的请求数。

func NewConcurrencyLimiter

func NewConcurrencyLimiter(max int) *ConcurrencyLimiter

NewConcurrencyLimiter 创建并发限制器;max <= 0 表示不限制。

func (*ConcurrencyLimiter) Active

func (l *ConcurrencyLimiter) Active() int64

Active 返回当前占用的并发额度。

func (*ConcurrencyLimiter) Rejected

func (l *ConcurrencyLimiter) Rejected() uint64

Rejected 返回因额度已满被拒绝的请求数。

func (*ConcurrencyLimiter) Release

func (l *ConcurrencyLimiter) Release()

Release 释放一个并发额度。

func (*ConcurrencyLimiter) SetMetricsSink

func (l *ConcurrencyLimiter) SetMetricsSink(sink MetricsSink)

SetMetricsSink 注入外部指标接收器(启动前调用,可为 nil)。

func (*ConcurrencyLimiter) SetRejectMessage

func (l *ConcurrencyLimiter) SetRejectMessage(msg string)

SetRejectMessage 设置拒绝响应文案;空字符串使用默认文案。

func (*ConcurrencyLimiter) TryAcquire

func (l *ConcurrencyLimiter) TryAcquire() bool

TryAcquire 尝试占用一个并发额度;额度已满返回 false。

type GaugeSink

type GaugeSink interface {
	// AddGauge 按增量调整瞬时量(如 +1/-1)。
	AddGauge(name string, delta float64, labels ...string)
	// SetGauge 设置瞬时量绝对值。
	SetGauge(name string, value float64, labels ...string)
}

GaugeSink 是可选的瞬时量扩展接口,实现时 webx 会上报 活跃请求与连接水位;未实现则自动跳过。

type GroupStat

type GroupStat struct {
	// Prefix 分组前缀。
	Prefix string
	// Requests 请求数。
	Requests uint64
	// Errors5xx 5xx 响应数。
	Errors5xx uint64
	// AvgDurationMs 平均请求耗时(毫秒)。
	AvgDurationMs uint64
}

GroupStat 单个路由分组的指标统计快照。

type GzipOptions

type GzipOptions struct {
	// MinSize 未显式写状态码时,小于该字节数的响应不压缩(0=默认 1024)。
	MinSize int
	// Level 压缩级别(0=标准库默认;1-9 对应 BestSpeed-BestCompression)。
	Level int
}

GzipOptions 定义响应压缩中间件的选项。

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager 管理内置中间件的注册表、执行顺序和启用状态。

func NewManager

func NewManager() *Manager

NewManager 创建中间件管理器。 默认启用全部内置中间件(RateLimit 注册但默认禁用)。

func (*Manager) Append

func (m *Manager) Append(handler ...core.HandlerFunc)

Append 追加外部全局中间件到中间件链末尾(路由专属中间件之前)。

func (*Manager) Build

func (m *Manager) Build(ctx context.Context) []core.HandlerFunc

Build 构建最终执行的中间件链。 返回顺序:内置(启用)→ 外部全局。

func (*Manager) Disable

func (m *Manager) Disable(mt ...string)

Disable 禁用指定类型的内置中间件。

func (*Manager) DisableRateLimit

func (m *Manager) DisableRateLimit()

DisableRateLimit 禁用限流中间件并移除其 Handler。

func (*Manager) Enable

func (m *Manager) Enable(mt ...string)

Enable 启用指定类型的内置中间件。 注意:RateLimit 必须通过 EnableRateLimit 激活,Enable 对其无效。

func (*Manager) EnableRateLimit

func (m *Manager) EnableRateLimit(handler core.HandlerFunc)

EnableRateLimit 启用限流中间件并注册其 Handler。

func (*Manager) Override

func (m *Manager) Override(mt string, handler core.HandlerFunc)

Override 覆盖指定类型的内置中间件。

func (*Manager) RegisterBuiltin

func (m *Manager) RegisterBuiltin(key string, handler core.HandlerFunc)

RegisterBuiltin 注册一个内置中间件到管理器。

func (*Manager) SetOrder

func (m *Manager) SetOrder(keys ...string)

SetOrder 设置内置中间件的执行顺序(未知键与空顺序忽略)。

type Metrics

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics 统计请求、状态码分布与协议维度指标,供监控面板对接。

func NewMetrics

func NewMetrics(sink MetricsSink) *Metrics

NewMetrics 创建指标计数器,sink 为外部指标接收器(可为 nil)。

func (*Metrics) Durations

func (m *Metrics) Durations() (totalNs, samples uint64)

Durations 返回累计耗时(纳秒)与样本数。

func (*Metrics) GroupStats

func (m *Metrics) GroupStats() []GroupStat

GroupStats 返回分组级统计快照(按分组前缀排序)。

func (*Metrics) InFlight

func (m *Metrics) InFlight() int64

InFlight 返回当前活跃请求数。

func (*Metrics) Panics

func (m *Metrics) Panics() uint64

Panics 返回 Recovery 捕获的 panic 数量。

func (*Metrics) ProtocolStats

func (m *Metrics) ProtocolStats() ProtocolStats

ProtocolStats 返回各协议(HTTP/1.x、HTTP/2、HTTP/3)的请求数与平均耗时(毫秒)。

func (*Metrics) RouteStats

func (m *Metrics) RouteStats() []RouteStat

RouteStats 返回路由级统计快照(按注册路径排序)。

func (*Metrics) Snapshot

func (m *Metrics) Snapshot() (requests, errors5x uint64)

Snapshot 返回当前计数快照。

func (*Metrics) StatusCodes

func (m *Metrics) StatusCodes() (s1xx, s2xx, s3xx, s4xx, s5xx uint64)

StatusCodes 返回按状态码分类的请求计数(1xx/2xx/3xx/4xx/5xx)。

type MetricsSink

type MetricsSink interface {
	// IncCounter 增加一个计数指标。
	IncCounter(name string, labels ...string)
	// ObserveDuration 记录一次耗时观测(秒)。
	ObserveDuration(name string, seconds float64, labels ...string)
}

MetricsSink 是外部指标接收器接口,metricsx 等家族底座天然满足。 未注入时仅保留内部快照统计,不产生外部开销。

type ProtocolStats

type ProtocolStats struct {
	// HTTP1Requests HTTP/1.0 与 HTTP/1.1 请求数。
	HTTP1Requests uint64
	// HTTP2Requests HTTP/2 请求数。
	HTTP2Requests uint64
	// HTTP3Requests HTTP/3 请求数。
	HTTP3Requests uint64
	// HTTP1AvgMs HTTP/1.x 平均耗时(毫秒)。
	HTTP1AvgMs uint64
	// HTTP2AvgMs HTTP/2 平均耗时(毫秒)。
	HTTP2AvgMs uint64
	// HTTP3AvgMs HTTP/3 平均耗时(毫秒)。
	HTTP3AvgMs uint64
}

ProtocolStats 协议维度请求统计快照。

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter 实现基于 IP 的令牌桶限流。

func NewRateLimiter

func NewRateLimiter(qps int, window time.Duration, whitelistCIDRs []string) *RateLimiter

NewRateLimiter 创建 IP 限流器。

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(ip string) bool

Allow 检查指定 IP 是否被允许通过。

func (*RateLimiter) Cleanup

func (rl *RateLimiter) Cleanup(interval time.Duration)

Cleanup 清理超过 window*10 未活动的桶。

func (*RateLimiter) Rejected

func (rl *RateLimiter) Rejected() uint64

Rejected 返回被拒绝的请求数。

func (*RateLimiter) RetryAfter

func (rl *RateLimiter) RetryAfter(key string) time.Duration

RetryAfter 返回指定 key 恢复 1 枚令牌所需的等待时间(秒,向上取整)。

func (*RateLimiter) SetKeyFunc

func (rl *RateLimiter) SetKeyFunc(fn func(*core.Context) string)

SetKeyFunc 设置限流维度提取函数(默认按客户端 IP)。

func (*RateLimiter) SetMaxBuckets

func (rl *RateLimiter) SetMaxBuckets(n int)

SetMaxBuckets 设置 IP 桶数量上限;达到上限后新 IP 直接拒绝。

func (*RateLimiter) SetMetricsSink

func (rl *RateLimiter) SetMetricsSink(sink MetricsSink)

SetMetricsSink 注入外部指标接收器(启动前调用,可为 nil)。

func (*RateLimiter) SetRejectMessage

func (rl *RateLimiter) SetRejectMessage(msg string)

SetRejectMessage 设置拒绝响应文案;空字符串使用默认文案。

type RequestIDOptions

type RequestIDOptions struct {
	// Header 请求 ID 头名(默认 X-Request-ID)。
	Header string
	// Generator 请求 ID 生成函数(默认 UUID v7)。
	Generator func() string
}

RequestIDOptions 定义请求 ID 中间件的配置参数。

type RouteStat

type RouteStat struct {
	// Path 路由注册路径。
	Path string
	// Requests 请求数。
	Requests uint64
	// Errors5xx 5xx 响应数。
	Errors5xx uint64
	// AvgDurationMs 平均请求耗时(毫秒)。
	AvgDurationMs uint64
}

RouteStat 单条路由的指标统计快照。

type SecurityHeadersOptions

type SecurityHeadersOptions struct {
	// ContentTypeNoSniff 设置 X-Content-Type-Options: nosniff。
	ContentTypeNoSniff bool
	// FrameDeny 设置 X-Frame-Options: DENY。
	FrameDeny bool
	// ReferrerPolicy 设置 Referrer-Policy(空则不设置)。
	ReferrerPolicy string
	// HSTSMaxAge 大于 0 时设置 Strict-Transport-Security。
	HSTSMaxAge time.Duration
	// PermissionsPolicy 设置 Permissions-Policy(空则不设置)。
	PermissionsPolicy string
	// CrossOriginOpenerPolicy 设置 Cross-Origin-Opener-Policy(空则不设置)。
	CrossOriginOpenerPolicy string
	// CrossOriginResourcePolicy 设置 Cross-Origin-Resource-Policy(空则不设置)。
	CrossOriginResourcePolicy string
	// CrossOriginEmbedderPolicy 设置 Cross-Origin-Embedder-Policy(空则不设置)。
	CrossOriginEmbedderPolicy string
	// ContentSecurityPolicy 设置 Content-Security-Policy(空则不设置)。
	ContentSecurityPolicy string
	// ContentSecurityPolicyReportOnly 设置 Content-Security-Policy-Report-Only(空则不设置)。
	ContentSecurityPolicyReportOnly string
	// HSTSIncludeSubDomains HSTS 指令附加 includeSubDomains。
	HSTSIncludeSubDomains bool
	// HSTSPreload HSTS 指令附加 preload。
	HSTSPreload bool
	// OriginAgentCluster 设置 Origin-Agent-Cluster: ?1(站点隔离)。
	OriginAgentCluster bool
}

SecurityHeadersOptions 定义安全响应头中间件的配置。

type TimeoutOptions

type TimeoutOptions struct {
	// Message 超时响应文案(默认 "请求处理超时")。
	Message string
}

TimeoutOptions 定义请求超时中间件的配置。

Jump to

Keyboard shortcuts

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