Documentation
¶
Overview ¶
Package middleware 提供可复用的 HTTP 中间件集合。
该包面向 `httpserver` 以及直接使用 Gin 的项目,提供 Recovery、Timeout、 TraceID、RequestID、AccessLog、Compression、ConcurrencyLimit、CORS、安全响应头和请求体大小限制等通用中间件。 其中 ConcurrencyLimit 用于单进程全局并发闸门,超限请求会立即返回 503,不排队等待。
Index ¶
- func AccessLog(configs ...AccessLogConfig) gin.HandlerFunc
- func CORS(config CORSConfig) gin.HandlerFunc
- func ClientIPFromRequest(r *http.Request) string
- func Compression(configs ...CompressionConfig) gin.HandlerFunc
- func ConcurrencyLimit(limit int) gin.HandlerFunc
- func ConcurrencyLimitWithConfig(config ConcurrencyLimitConfig) gin.HandlerFunc
- func MaxBodySize(limit int64) gin.HandlerFunc
- func RateLimit(rps float64) gin.HandlerFunc
- func RateLimitWithConfig(config RateLimitConfig) gin.HandlerFunc
- func RealIP() gin.HandlerFunc
- func RealIPWithConfig(config RealIPConfig) gin.HandlerFunc
- func Recovery() gin.HandlerFunc
- func RecoveryWithConfig(config RecoveryConfig) gin.HandlerFunc
- func RequestID() gin.HandlerFunc
- func SecurityHeaders() gin.HandlerFunc
- func SecurityHeadersWithConfig(config SecurityHeadersConfig) gin.HandlerFunc
- func Timeout(timeout time.Duration) gin.HandlerFunc
- func TimeoutWithConfig(config TimeoutConfig) gin.HandlerFunc
- func TraceID() gin.HandlerFunc
- type AccessLogConfig
- type CORSConfig
- type CompressionConfig
- type ConcurrencyLimitConfig
- type LoggerFunc
- type MultipartCaptureMode
- type MultipartConfig
- type RateLimitConfig
- type RealIPConfig
- type RecoveryConfig
- type RedactionConfig
- type RedactionRule
- type RedactionStrategy
- type SecurityHeadersConfig
- type TimeoutConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClientIPFromRequest ¶
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 RateLimitWithConfig ¶
func RateLimitWithConfig(config RateLimitConfig) gin.HandlerFunc
RateLimitWithConfig 使用自定义配置创建速率限制中间件。
func RealIPWithConfig ¶
func RealIPWithConfig(config RealIPConfig) gin.HandlerFunc
RealIPWithConfig 使用自定义配置创建中间件。
func RecoveryWithConfig ¶
func RecoveryWithConfig(config RecoveryConfig) gin.HandlerFunc
RecoveryWithConfig 使用自定义配置创建 Recovery 中间件。
func SecurityHeadersWithConfig ¶
func SecurityHeadersWithConfig(config SecurityHeadersConfig) gin.HandlerFunc
SecurityHeadersWithConfig 使用自定义配置创建安全头中间件。
func TimeoutWithConfig ¶
func TimeoutWithConfig(config TimeoutConfig) gin.HandlerFunc
TimeoutWithConfig 使用自定义配置创建超时中间件。
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 ¶
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 描述安全响应头行为。