middleware

package
v1.1.7 Latest Latest
Warning

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

Go to latest
Published: May 7, 2025 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultCSRFCookieName     = "csrf_token"
	DefaultCSRFHeaderName     = "X-CSRF-TOKEN"
	DefaultCSRFParameterName  = "_csrf"
	DefaultCSRFContextKey     = "csrf"
	DefaultCSRFTokenLength    = 32
	DefaultCSRFTokenExpiry    = time.Hour * 24
	DefaultCSRFSingleUseToken = false
)

默认设置

View Source
const (
	LogToConsole = iota
	LogToFile
	LogToDatabase
)

日志记录输出位置

View Source
const (
	LogLevelBasic = iota
	LogLevelStandard
	LogLevelDetailed
	LogLevelFull
)

日志详细程度级别

Variables

View Source
var (
	ErrCSRFTokenInvalid   = errors.New("CSRF令牌无效")
	ErrCSRFTokenNotFound  = errors.New("未找到CSRF令牌")
	ErrCSRFTokenUsed      = errors.New("CSRF令牌已使用")
	ErrCSRFTokenExpired   = errors.New("CSRF令牌已过期")
	ErrCSRFHeaderNotSet   = errors.New("缺少CSRF头")
	ErrCSRFCookieNotFound = errors.New("CSRF Cookie不存在")
)

CSRF错误常量

View Source
var (
	ErrJWTTokenMissing      = errors.New("令牌缺失")
	ErrJWTTokenInvalid      = errors.New("令牌无效")
	ErrJWTTokenExpired      = errors.New("令牌已过期")
	ErrJWTTokenNotActive    = errors.New("令牌尚未生效")
	ErrJWTUnexpectedSigning = errors.New("意外的签名方法")
)

JWT错误定义

View Source
var (
	ErrRateLimitExceeded = errors.New("请求频率超出限制")
)

存储器错误定义

Functions

func CORS

func CORS() flow.HandlerFunc

CORS 返回一个CORS中间件,允许所有源访问

func CORSWithConfig

func CORSWithConfig(config CORSConfig) flow.HandlerFunc

CORSWithConfig 返回一个使用指定配置的CORS中间件

func CSRF

func CSRF() flow.HandlerFunc

CSRF 使用默认配置创建CSRF中间件

func CSRFRequired

func CSRFRequired(config CSRFConfig) flow.HandlerFunc

CSRFRequired 提供更细粒度的验证,可在特定路由上启用

func CSRFWithConfig

func CSRFWithConfig(config CSRFConfig) flow.HandlerFunc

CSRFWithConfig 使用自定义配置创建CSRF中间件

func CreateToken

func CreateToken(claims jwt.Claims, key interface{}, method jwt.SigningMethod) (string, error)

CreateToken 创建一个新的JWT令牌

func CreateTokenWithExp

func CreateTokenWithExp(id string, issuer string, audience string, subject string, expiry time.Duration, key interface{}, method jwt.SigningMethod) (string, error)

CreateTokenWithExp 创建一个带有过期时间的令牌

func GenerateCSRFHTML

func GenerateCSRFHTML(c *flow.Context) template.HTML

GenerateCSRFHTML 生成包含CSRF令牌的HTML表单字段

func GenerateCSRFToken

func GenerateCSRFToken(config CSRFConfig) flow.HandlerFunc

GenerateCSRFToken 生成CSRF令牌并返回

func GenerateCSRFTokenHash

func GenerateCSRFTokenHash(token, secret string) string

GenerateCSRFTokenHash 根据密钥生成令牌哈希

func GetCSRFToken

func GetCSRFToken(c *flow.Context) string

GetCSRFToken 获取当前的CSRF令牌

func GetLocale

func GetLocale(c *gin.Context) string

GetLocale 从Gin上下文获取当前语言

func IPRateLimit

func IPRateLimit(max int, duration time.Duration) flow.HandlerFunc

IPRateLimit 创建IP级别的速率限制中间件

func JWT

func JWT(key interface{}) flow.HandlerFunc

JWT 返回使用默认配置的JWT中间件

func JWTWithConfig

func JWTWithConfig(config JWTConfig) flow.HandlerFunc

JWTWithConfig 返回使用自定义配置的JWT中间件

func Locale

func Locale(translator i18n.Translator, opts ...*LocaleOptions) gin.HandlerFunc

Locale 创建一个本地化中间件

func Logger

func Logger() flow.HandlerFunc

Logger 返回一个日志中间件

func LoggerWithConfig

func LoggerWithConfig(config LoggerConfig) flow.HandlerFunc

LoggerWithConfig 返回一个使用指定配置的日志中间件

func ProtectForm

func ProtectForm(formHTML string, c *flow.Context) string

ProtectForm 保护表单免受CSRF攻击的辅助函数

func RateLimit

func RateLimit() flow.HandlerFunc

RateLimit 创建速率限制中间件,使用默认配置

func RateLimitWithConfig

func RateLimitWithConfig(config RateLimiterConfig) flow.HandlerFunc

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

func RateLimitWithMax

func RateLimitWithMax(max int, duration time.Duration) flow.HandlerFunc

RateLimitWithMax 创建具有指定最大请求数和持续时间的速率限制中间件

func Record

func Record(config RecordConfig) gin.HandlerFunc

Record 返回记录请求和响应的中间件

func Recovery

func Recovery() flow.HandlerFunc

Recovery 返回一个恢复中间件

func RecoveryWithConfig

func RecoveryWithConfig(config RecoveryConfig) flow.HandlerFunc

RecoveryWithConfig 返回一个使用指定配置的恢复中间件

func RouteRateLimit

func RouteRateLimit(routes map[string]int, duration time.Duration) flow.HandlerFunc

RouteRateLimit 创建路由级别的速率限制中间件

func UserRateLimit

func UserRateLimit(max int, duration time.Duration, userExtractor func(*flow.Context) string) flow.HandlerFunc

UserRateLimit 创建用户级别的速率限制中间件

func WithRequestID

func WithRequestID() gin.HandlerFunc

WithRequestID 添加请求ID的中间件

Types

type CORSConfig

type CORSConfig struct {
	// AllowOrigins 是允许的源列表,例如 ["https://example.com"]
	// 特殊的 "*" 表示允许所有源
	AllowOrigins []string

	// AllowMethods 是允许的HTTP方法列表
	// 默认是 ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"]
	AllowMethods []string

	// AllowHeaders 是允许的HTTP头部列表
	// 默认是 ["Origin", "Content-Type", "Content-Length", "Accept", "Authorization"]
	AllowHeaders []string

	// ExposeHeaders 是客户端可以访问的自定义头部列表
	ExposeHeaders []string

	// AllowCredentials 表示请求中是否可以包含用户凭证
	AllowCredentials bool

	// MaxAge 表示预检请求的结果可以缓存多长时间(秒)
	MaxAge int

	// AllowPrivateNetwork 指示是否允许私有网络请求
	AllowPrivateNetwork bool
}

CORSConfig 是CORS中间件的配置选项

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig 返回CORS中间件的默认配置

type CSRFConfig

type CSRFConfig struct {
	// TokenLength 指定CSRF令牌的长度
	TokenLength int

	// TokenExpiry 指定CSRF令牌的过期时间
	TokenExpiry time.Duration

	// CookieName 指定存储CSRF令牌的Cookie名称
	CookieName string

	// CookiePath 指定Cookie的路径
	CookiePath string

	// CookieDomain 指定Cookie的域
	CookieDomain string

	// CookieSecure 指定Cookie是否只通过HTTPS发送
	CookieSecure bool

	// CookieHTTPOnly 指定Cookie是否只能通过HTTP访问
	CookieHTTPOnly bool

	// CookieSameSite 指定Cookie的SameSite策略
	CookieSameSite http.SameSite

	// HeaderName 指定CSRF头名称
	HeaderName string

	// ParameterName 指定CSRF表单参数名称
	ParameterName string

	// ContextKey 指定存储在上下文中的键名
	ContextKey string

	// Secret 用于签名CSRF令牌的密钥
	Secret string

	// ErrorFunc 自定义错误处理函数
	ErrorFunc func(*flow.Context, error)

	// TokenStore 令牌存储接口
	TokenStore TokenStore

	// ExcludeURLs 排除的URL列表
	ExcludeURLs []string

	// AllowedOrigins 允许的源列表
	AllowedOrigins []string

	// AllowedMethods 允许的HTTP方法列表,不检查CSRF
	AllowedMethods []string

	// SingleUseToken 是否为单次使用令牌
	SingleUseToken bool
}

CSRFConfig 定义CSRF中间件配置

func DefaultCSRFConfig

func DefaultCSRFConfig() CSRFConfig

DefaultCSRFConfig 返回默认CSRF配置

type ConsoleLogWriter

type ConsoleLogWriter struct{}

ConsoleLogWriter 实现控制台日志写入

func (*ConsoleLogWriter) Close

func (w *ConsoleLogWriter) Close() error

Close 实现接口

func (*ConsoleLogWriter) WriteLog

func (w *ConsoleLogWriter) WriteLog(entry *RequestLogEntry) error

WriteLog 将日志条目写入控制台

type Counter

type Counter struct {
	// 计数值
	Value int
	// 过期时间
	Expiry time.Time
}

Counter 计数器结构

type ErrorLogWriterFunc

type ErrorLogWriterFunc func(error)

ErrorLogWriterFunc 是错误日志写入函数

type FileLogWriter

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

FileLogWriter 实现文件日志写入

func NewFileLogWriter

func NewFileLogWriter(filePath string) (*FileLogWriter, error)

NewFileLogWriter 创建新的文件日志写入器

func (*FileLogWriter) Close

func (w *FileLogWriter) Close() error

Close 关闭文件

func (*FileLogWriter) WriteLog

func (w *FileLogWriter) WriteLog(entry *RequestLogEntry) error

WriteLog 将日志条目写入文件

type HTTPError

type HTTPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

HTTPError 表示HTTP错误

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error 实现error接口

type JWTConfig

type JWTConfig struct {
	// 从请求中提取token的函数
	TokenExtractor func(*flow.Context) (string, error)

	// 用于签名的密钥
	SigningKey interface{}

	// 用于验证的密钥
	ValidationKey interface{}

	// 签名方法
	SigningMethod jwt.SigningMethod

	// 令牌在上下文中的键
	ContextKey string

	// 处理令牌错误的回调函数
	ErrorHandler func(*flow.Context, error)

	// 路径白名单,这些路径不需要检查令牌
	Skipper func(*flow.Context) bool

	// 令牌查找顺序:1. 查询参数,2. Cookie,3. 请求头
	TokenLookup string

	// 请求头中包含令牌的头部名称
	AuthScheme string

	// 是否使用令牌黑名单
	UseBlacklist bool

	// 黑名单检查函数
	BlacklistCheck func(string) bool
}

JWTConfig JWT中间件的配置

func DefaultJWTConfig

func DefaultJWTConfig() JWTConfig

DefaultJWTConfig 返回JWT中间件的默认配置

type LocaleOptions

type LocaleOptions struct {
	// 默认语言
	DefaultLocale string

	// 翻译器
	Translator i18n.Translator

	// 支持的语言列表
	SupportedLocales []string

	// 从查询参数获取语言的键名
	QueryParameterName string

	// 从Cookie获取语言的键名
	CookieName string

	// 从Header获取语言的键名
	HeaderName string

	// 是否自动保存语言到Cookie
	SaveToCookie bool

	// Cookie有效期(秒)
	CookieMaxAge int

	// Cookie路径
	CookiePath string

	// 是否创建子域名Cookie
	CookieSecure bool

	// 是否只允许HTTP访问Cookie
	CookieHTTPOnly bool

	// 是否使用会话Cookie(会话结束就过期)
	CookieSession bool

	// 是否自动检测浏览器语言
	DetectBrowserLocale bool
}

LocaleOptions 本地化中间件的选项

func DefaultLocaleOptions

func DefaultLocaleOptions() *LocaleOptions

DefaultLocaleOptions 返回默认的本地化选项

type LoggerConfig

type LoggerConfig struct {
	// SkipPaths 是不需要记录日志的路径
	SkipPaths []string

	// LogLevel 是日志级别
	LogLevel logrus.Level

	// Formatter 是日志格式化器
	Formatter logrus.Formatter

	// Output 是日志输出目标
	Output logrus.FieldLogger
}

LoggerConfig 是日志中间件的配置选项

func LoggerDefaultConfig

func LoggerDefaultConfig() LoggerConfig

LoggerDefaultConfig 返回日志中间件的默认配置

type MemoryStore

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

MemoryStore 内存存储实现

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore 创建内存存储

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, key string) (int, error)

Get 获取当前计数

func (*MemoryStore) Increment

func (s *MemoryStore) Increment(ctx context.Context, key string, expiry time.Duration) (int, error)

Increment 增加计数器

func (*MemoryStore) Reset

func (s *MemoryStore) Reset(ctx context.Context, key string) error

Reset 重置计数器

type MemoryTokenStore

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

MemoryTokenStore 内存令牌存储实现

func NewMemoryTokenStore

func NewMemoryTokenStore() *MemoryTokenStore

NewMemoryTokenStore 创建一个新的内存令牌存储

func (*MemoryTokenStore) DeleteToken

func (s *MemoryTokenStore) DeleteToken(ctx *flow.Context, token string) error

DeleteToken 删除CSRF令牌

func (*MemoryTokenStore) GenerateToken

func (s *MemoryTokenStore) GenerateToken(ctx *flow.Context) (string, error)

GenerateToken 生成一个新的CSRF令牌

func (*MemoryTokenStore) ValidateToken

func (s *MemoryTokenStore) ValidateToken(ctx *flow.Context, token string) bool

ValidateToken 验证CSRF令牌

type RateLimiterConfig

type RateLimiterConfig struct {
	// 存储器
	Store RateLimiterStore
	// 最大请求数
	Max int
	// 时间窗口
	Duration time.Duration
	// 键生成函数
	KeyGenerator func(*flow.Context) string
	// 忽略规则
	Skipper func(*flow.Context) bool
	// 错误处理函数
	ErrorHandler func(*flow.Context, error)
	// 头部名称
	HeaderEnabled bool
	// 头部名称前缀
	HeaderPrefix string
}

RateLimiterConfig 速率限制器配置

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() RateLimiterConfig

DefaultRateLimiterConfig 返回默认的速率限制器配置

type RateLimiterStore

type RateLimiterStore interface {
	// Increment 增加计数器并返回当前计数
	Increment(ctx context.Context, key string, expiry time.Duration) (int, error)
	// Reset 重置计数器
	Reset(ctx context.Context, key string) error
	// Get 获取当前计数
	Get(ctx context.Context, key string) (int, error)
}

RateLimiterStore 速率限制器存储接口

type RecordConfig

type RecordConfig struct {
	// 日志输出位置: LogToConsole, LogToFile, LogToDatabase
	LogDestination int
	// 日志文件路径,当LogDestination为LogToFile时使用
	LogFilePath string
	// 自定义日志写入器,如果提供则忽略LogDestination
	LogWriter RecordLogWriter
	// 日志详细级别: LogLevelBasic, LogLevelStandard, LogLevelDetailed, LogLevelFull
	LogLevel int
	// 是否屏蔽敏感信息
	MaskSensitiveData bool
	// 自定义敏感字段列表,补充默认的正则表达式
	SensitiveFields []string
	// 请求路径排除列表,这些路径不会被记录
	SkipPaths []string
	// 记录请求体的最大大小(字节)
	MaxBodySize int
	// 错误处理函数
	ErrorLogWriter ErrorLogWriterFunc
	// 是否记录健康检查请求
	SkipHealthChecks bool
	// 健康检查路径
	HealthCheckPath string
}

RecordConfig 配置请求记录中间件的行为

func DefaultRecordConfig

func DefaultRecordConfig() RecordConfig

DefaultRecordConfig 返回默认记录配置

type RecordLogWriter

type RecordLogWriter interface {
	WriteLog(entry *RequestLogEntry) error
	Close() error
}

RecordLogWriter 接口定义了日志写入器

type RecoveryConfig

type RecoveryConfig struct {
	// DisableStackAll 禁用完整堆栈跟踪
	DisableStackAll bool

	// DisablePrintStack 禁用打印堆栈信息
	DisablePrintStack bool

	// MaxStackSize 最大堆栈大小
	MaxStackSize int
}

RecoveryConfig 是恢复中间件的配置选项

func RecoveryDefaultConfig

func RecoveryDefaultConfig() RecoveryConfig

RecoveryDefaultConfig 返回恢复中间件的默认配置

type RedisStore

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

RedisStore Redis存储实现

func NewRedisStore

func NewRedisStore(client *redis.Client, prefix string) *RedisStore

NewRedisStore 创建Redis存储

func (*RedisStore) Get

func (s *RedisStore) Get(ctx context.Context, key string) (int, error)

Get 获取当前计数

func (*RedisStore) Increment

func (s *RedisStore) Increment(ctx context.Context, key string, expiry time.Duration) (int, error)

Increment 增加计数器

func (*RedisStore) Reset

func (s *RedisStore) Reset(ctx context.Context, key string) error

Reset 重置计数器

type RedisTokenStore

type RedisTokenStore struct {
}

RedisTokenStore Redis令牌存储实现

type RequestLogEntry

type RequestLogEntry struct {
	Timestamp       time.Time     `json:"timestamp"`
	RequestID       string        `json:"request_id"`
	ClientIP        string        `json:"client_ip"`
	Method          string        `json:"method"`
	Path            string        `json:"path"`
	Query           string        `json:"query,omitempty"`
	UserAgent       string        `json:"user_agent,omitempty"`
	RequestHeaders  interface{}   `json:"request_headers,omitempty"`
	RequestBody     interface{}   `json:"request_body,omitempty"`
	ResponseStatus  int           `json:"response_status"`
	ResponseSize    int           `json:"response_size,omitempty"`
	ResponseHeaders interface{}   `json:"response_headers,omitempty"`
	ResponseBody    interface{}   `json:"response_body,omitempty"`
	Latency         time.Duration `json:"latency"`
	Error           string        `json:"error,omitempty"`
}

RequestLogEntry 包含请求和响应日志信息

type ResponseBodyWriter

type ResponseBodyWriter struct {
	gin.ResponseWriter
	// contains filtered or unexported fields
}

ResponseBodyWriter 自定义响应体写入器,用于捕获响应

func (ResponseBodyWriter) Write

func (w ResponseBodyWriter) Write(b []byte) (int, error)

Write 捕获写入的响应体

func (ResponseBodyWriter) WriteString

func (w ResponseBodyWriter) WriteString(s string) (int, error)

WriteString 捕获写入的字符串

type TokenExtractorFunc

type TokenExtractorFunc func(*flow.Context) (string, error)

TokenExtractorFunc 函数类型用于从请求中提取令牌

type TokenStore

type TokenStore interface {
	// GenerateToken 生成一个新的CSRF令牌
	GenerateToken(ctx *flow.Context) (string, error)

	// ValidateToken 验证CSRF令牌
	ValidateToken(ctx *flow.Context, token string) bool

	// DeleteToken 删除CSRF令牌
	DeleteToken(ctx *flow.Context, token string) error
}

TokenStore 定义了CSRF令牌存储接口

Jump to

Keyboard shortcuts

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