middleware

package
v0.0.0-...-0409f2c Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplySecurityMiddleware

func ApplySecurityMiddleware(r *gin.RouterGroup)

ApplySecurityMiddleware 应用安全中间件到路由组

func CSRFMiddleware

func CSRFMiddleware(config *SecurityConfig) gin.HandlerFunc

CSRFMiddleware CSRF保护中间件

func CompressionMiddleware

func CompressionMiddleware(config *CompressionConfig) gin.HandlerFunc

CompressionMiddleware creates compression middleware

func CorsMiddleware

func CorsMiddleware() gin.HandlerFunc

CorsMiddleware 跨域处理中间件

func CreateOperationLog

func CreateOperationLog(db *gorm.DB, userID uint, username, action, target, details, ipAddress, userAgent, referer, device, browser, operatingSystem, location, requestMethod string) error

CreateOperationLog creates an operation log

func GetCarrotSessionField

func GetCarrotSessionField() string

func GetRequestID

func GetRequestID(c *gin.Context) string

GetRequestID gets request ID from context

func InjectDB

func InjectDB(db *gorm.DB) gin.HandlerFunc

InjectDB 注入数据库实例到 Gin 上下文

func InputValidationMiddleware

func InputValidationMiddleware() gin.HandlerFunc

InputValidationMiddleware 输入验证中间件

func LoggerMiddleware

func LoggerMiddleware(logger *zap.Logger) gin.HandlerFunc

LoggerMiddleware 请求日志中间件

func OperationLogMiddleware

func OperationLogMiddleware() gin.HandlerFunc

OperationLogMiddleware records operation logs

func RateLimiterMiddleware

func RateLimiterMiddleware() gin.HandlerFunc

RateLimiterMiddleware 企业级限流中间件(全局版,兼容原接口)

func RecoveryMiddleware

func RecoveryMiddleware(logger *zap.Logger) gin.HandlerFunc

RecoveryMiddleware recovers from panics and logs the error

func RequestIDMiddleware

func RequestIDMiddleware() gin.HandlerFunc

RequestIDMiddleware adds a unique request ID to each request

func SanitizeString

func SanitizeString(input string) string

SanitizeString 清理字符串,移除危险字符

func SecureCompare

func SecureCompare(a, b string) bool

SecureCompare 安全比较字符串,防止时序攻击

func SecurityMiddleware

func SecurityMiddleware(config *SecurityConfig) gin.HandlerFunc

SecurityMiddleware 安全中间件

func SecurityMiddlewareChain

func SecurityMiddlewareChain() []gin.HandlerFunc

SecurityMiddlewareChain 安全中间件链

func SetRateLimiterConfig

func SetRateLimiterConfig(config RateLimiterConfig)

SetRateLimiterConfig 动态更新限流配置

func SetRateLimiterStore

func SetRateLimiterStore(store limiter.Store)

SetRateLimiterStore 注入外部存储(如 Redis store)

func SignVerifyMiddleware

func SignVerifyMiddleware() gin.HandlerFunc

API 签名验证中间件

func TimeoutMiddleware

func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc

TimeoutMiddleware creates a timeout middleware

func ValidateEmail

func ValidateEmail(email string) bool

ValidateEmail 验证邮箱格式

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword 验证密码强度

func WithCookieSession

func WithCookieSession(secret string, maxAge int) gin.HandlerFunc

func WithMemSession

func WithMemSession(secret string) gin.HandlerFunc

func XSSProtectionMiddleware

func XSSProtectionMiddleware() gin.HandlerFunc

XSSProtectionMiddleware XSS防护中间件

Types

type CompressionConfig

type CompressionConfig struct {
	// Compression level (1-9, default: 6)
	Level int
	// Minimum content length to compress (default: 1024 bytes)
	MinLength int
	// Content types to compress
	ContentTypes []string
	// Exclude paths from compression
	ExcludePaths []string
}

CompressionConfig represents compression middleware configuration

func DefaultCompressionConfig

func DefaultCompressionConfig() *CompressionConfig

DefaultCompressionConfig returns default compression configuration

type MetricsObserver

type MetricsObserver interface {
	OnAllow(route string, key string)
	OnDeny(route string, key string)
}

MetricsObserver 指标上报接口 可接 Prometheus、StatsD 等

type OperationLog

type OperationLog struct {
	ID              uint      `gorm:"primaryKey" json:"id"`
	UserID          uint      `gorm:"not null" json:"user_id"`          // User ID who performed the operation
	Username        string    `gorm:"not null" json:"username"`         // Username who performed the operation
	Action          string    `gorm:"not null" json:"action"`           // Operation type (e.g., create, delete, update)
	Target          string    `gorm:"not null" json:"target"`           // Operation target (e.g., user, order)
	Details         string    `gorm:"not null" json:"details"`          // Operation detailed description
	IPAddress       string    `gorm:"not null" json:"ip_address"`       // User IP address
	UserAgent       string    `gorm:"not null" json:"user_agent"`       // User browser information
	Referer         string    `gorm:"not null" json:"referer"`          // Request referer page
	Device          string    `gorm:"not null" json:"device"`           // User device (mobile, desktop, etc.)
	Browser         string    `gorm:"not null" json:"browser"`          // Browser information (e.g., Chrome, Firefox)
	OperatingSystem string    `gorm:"not null" json:"operating_system"` // Operating system (e.g., Windows, MacOS)
	Location        string    `gorm:"not null" json:"location"`         // User geographic location
	RequestMethod   string    `gorm:"not null" json:"request_method"`   // HTTP request method (GET, POST, etc.)
	CreatedAt       time.Time `json:"created_at"`                       // Operation time
}

OperationLog represents user operation log

func (OperationLog) TableName

func (OperationLog) TableName() string

TableName specifies table name

type OperationLogConfig

type OperationLogConfig struct {
	// Whether to enable operation logging
	Enabled bool
	// Whether to log query operations
	LogQueries bool
	// Important operation patterns
	ImportantPatterns map[string][]string
	// Unimportant POST operations
	UnimportantPostPaths []string
	// System internal operation paths
	SystemInternalPaths []string
	// Operation description mapping
	OperationDescriptions map[string]string
}

OperationLogConfig represents operation log configuration

func DefaultOperationLogConfig

func DefaultOperationLogConfig() *OperationLogConfig

DefaultOperationLogConfig returns default configuration

func (*OperationLogConfig) GetOperationDescription

func (config *OperationLogConfig) GetOperationDescription(method, path string) string

GetOperationDescription gets operation description

func (*OperationLogConfig) ShouldLogOperation

func (config *OperationLogConfig) ShouldLogOperation(method, path string) bool

ShouldLogOperation determines whether to log operation based on configuration

type PrebuiltStoreFactory

type PrebuiltStoreFactory struct{ Store limiter.Store }

PrebuiltStoreFactory 直接复用已有的 limiter.Store(例如外部创建的 Redis store)

func (*PrebuiltStoreFactory) Create

func (p *PrebuiltStoreFactory) Create() limiter.Store

type PrometheusObserver

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

PrometheusObserver 基于 Prometheus 的实现

func NewPrometheusObserver

func NewPrometheusObserver() *PrometheusObserver

NewPrometheusObserver creates a Prometheus observer (singleton pattern to avoid duplicate registration)

func (*PrometheusObserver) OnAllow

func (p *PrometheusObserver) OnAllow(route, key string)

func (*PrometheusObserver) OnDeny

func (p *PrometheusObserver) OnDeny(route, key string)

type RateLimiter

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

RateLimiter 面向实例的限流器,支持按路由缓存多个 limiter

func NewRateLimiter

func NewRateLimiter(cfg RateLimiterConfig, store limiter.Store) *RateLimiter

NewRateLimiter 构造函数(推荐使用),避免全局依赖

func (*RateLimiter) Middleware

func (l *RateLimiter) Middleware() gin.HandlerFunc

Middleware 返回 Gin 中间件

func (*RateLimiter) UpdateConfig

func (l *RateLimiter) UpdateConfig(cfg RateLimiterConfig)

func (*RateLimiter) WithObserver

func (l *RateLimiter) WithObserver(observer MetricsObserver) *RateLimiter

WithObserver 配置指标观察者

func (*RateLimiter) WithStoreFactory

func (l *RateLimiter) WithStoreFactory(factory StoreFactory) *RateLimiter

WithStoreFactory 配置存储工厂

type RateLimiterConfig

type RateLimiterConfig struct {
	Rate           string            `json:"rate"`            // e.g. "100-M", "1000-H"
	PerRouteRates  map[string]string `json:"per_route_rates"` // 路由覆盖速率
	Identifier     string            `json:"identifier"`      // ip|user|header|ip+route
	HeaderName     string            `json:"header_name"`     // 当 identifier=header 时使用
	WhitelistCIDRs []string          `json:"whitelist_cidrs"`
	BlacklistCIDRs []string          `json:"blacklist_cidrs"`
	WhitelistUsers []string          `json:"whitelist_users"`
	BlacklistUsers []string          `json:"blacklist_users"`
	SkipPaths      []string          `json:"skip_paths"`
	AddHeaders     bool              `json:"add_headers"`
	DenyStatus     int               `json:"deny_status"` // 默认 429
	DenyMessage    string            `json:"deny_message"`
}

RateLimiterConfig 企业级限流配置

示例: Rate: "100-M"、Identifier: "ip"/"user"/"header"、HeaderName: "X-Client-ID" PerRouteRates: {"/api/v1/heavy": "10-S", "/api/v1/normal": "100-S"} WhitelistCIDRs/BlacklistCIDRs: ["10.0.0.0/8", "127.0.0.1/32"] WhitelistUsers/BlacklistUsers: ["admin", "ops-*"] 支持前缀匹配 SkipPaths: ["/health", "/metrics", "/static/"] 前缀匹配 AddHeaders: 是否写标准限流响应头;DenyStatus/DenyMessage: 自定义拒绝响应

Store 采用内存,可通过 SetRateLimiterStore 注入外部存储(如 Redis)。

func GetRateLimiterConfig

func GetRateLimiterConfig() RateLimiterConfig

GetRateLimiterConfig 获取当前配置(拷贝)

type SecurityConfig

type SecurityConfig struct {
	// CSRF配置
	CSRFSecret    string            `json:"csrf_secret"`
	CSRFTokenName string            `json:"csrf_token_name"`
	CSRFMaxAge    time.Duration     `json:"csrf_max_age"`
	CSRFSecure    bool              `json:"csrf_secure"`
	CSRFHttpOnly  bool              `json:"csrf_http_only"`
	CSRFSameSite  csrf.SameSiteMode `json:"csrf_same_site"`

	// XSS配置
	XSSProtection      bool   `json:"xss_protection"`
	ContentTypeNosniff bool   `json:"content_type_nosniff"`
	XFrameOptions      string `json:"x_frame_options"`

	// 输入验证配置
	MaxRequestSize int64    `json:"max_request_size"`
	AllowedOrigins []string `json:"allowed_origins"`

	// 安全头配置
	HSTSMaxAge     int    `json:"hsts_max_age"`
	ReferrerPolicy string `json:"referrer_policy"`
}

SecurityConfig 安全配置

func DefaultSecurityConfig

func DefaultSecurityConfig() *SecurityConfig

DefaultSecurityConfig 默认安全配置

type StoreFactory

type StoreFactory interface {
	Create() limiter.Store
}

StoreFactory 用于按需创建 store(例如基于 Redis 客户端)

type UserInfo

type UserInfo struct {
	ID          uint   // User ID
	DisplayName string // User display name
}

UserInfo represents user information for operation logging

Jump to

Keyboard shortcuts

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