Documentation
¶
Index ¶
- Constants
- func APIVersionMiddleware() gin.HandlerFunc
- func AuthRateLimiter(perWindow int, window time.Duration, burst int) gin.HandlerFunc
- func CORS() gin.HandlerFunc
- func CORSWithConfig(cfg CORSConfig) gin.HandlerFunc
- func CSRFMiddleware(config *SecurityConfig) gin.HandlerFunc
- func CircuitBreakerMiddleware() gin.HandlerFunc
- func CombinedTimeoutCircuitMiddleware() gin.HandlerFunc
- func DeprecationHeaders(sunset string) gin.HandlerFunc
- func ErrorHandler() gin.HandlerFunc
- func GetCircuitBreakerStats() map[string]interface{}
- func IPACLDecision(globalBlocked, globalAllowed, routeBlocked, routeAllowed IPList, ...) (allowed bool, reason string)
- func InitRedisRateBackend(addr, password string) error
- func InitTimeoutCircuitManager(timeoutCfg TimeoutConfig, cbCfg CircuitBreakerConfig, ...)
- func InjectDB(db *gorm.DB) gin.HandlerFunc
- func InputValidationMiddleware() gin.HandlerFunc
- func LoggerMiddleware(log *zap.Logger) gin.HandlerFunc
- func MaintenanceMode(bypass MaintenanceBypassFunc) gin.HandlerFunc
- func MarkOperationLogged(c *gin.Context)
- func OperationAlreadyLogged(c *gin.Context) bool
- func PanicRecovery() gin.HandlerFunc
- func RedisAllow(key string, limit int, window time.Duration) bool
- func RedisRateEnabled() bool
- func ReqIDFromGin(c *gin.Context) string
- func RequestIDMiddleware() gin.HandlerFunc
- func SanitizeString(input string) string
- func SecureCompare(a, b string) bool
- func SecurityMiddleware(config *SecurityConfig) gin.HandlerFunc
- func SetMaintenanceAllowedPaths(paths, prefixes []string)
- func SetSkipAccessLogPaths(paths []string)
- func TimeoutMiddleware() gin.HandlerFunc
- func URLBlacklistMiddleware(bl *URLBlacklist) gin.HandlerFunc
- func URLBlacklistMiddlewareWithHandler(bl *URLBlacklist, handler gin.HandlerFunc) gin.HandlerFunc
- func ValidateEmail(email string) bool
- func ValidatePassword(password string) error
- func WriteError(c *gin.Context, err error)
- func XSSProtectionMiddleware() gin.HandlerFunc
- type Breaker
- type BreakerFactory
- type CORSConfig
- type CircuitBreaker
- type CircuitBreakerConfig
- type CircuitBreakerState
- type IPACLRule
- type IPList
- type MaintenanceBypassFunc
- type SecurityConfig
- type TimeoutCircuitManager
- type TimeoutConfig
- type URLBlacklist
Constants ¶
const ( HeaderAPIVersion = "X-API-Version" APIVersionV1 = "v1" )
const ( EnvMaintenanceMode = "MAINTENANCE_MODE" EnvMaintenanceMessage = "MAINTENANCE_MESSAGE" )
Variables ¶
This section is empty.
Functions ¶
func APIVersionMiddleware ¶
func APIVersionMiddleware() gin.HandlerFunc
APIVersionMiddleware accepts X-API-Version (default v1), echoes it on the response, and returns 400 for unsupported versions (only v1 today).
func AuthRateLimiter ¶
AuthRateLimiter returns a gin middleware that throttles requests by client IP. perWindow specifies how many requests are allowed in the rolling window of length window; burst is the initial token bucket capacity (controls "thundering" behaviour at process start).
Returns 429 with a Retry-After-style hint when the limit is exceeded. nil-safe: zero values fall back to safe defaults (5 req / 5 min).
func CORSWithConfig ¶
func CORSWithConfig(cfg CORSConfig) gin.HandlerFunc
CORSWithConfig 返回一个自定义配置的 CORS 中间件。
func CSRFMiddleware ¶
func CSRFMiddleware(config *SecurityConfig) gin.HandlerFunc
CSRFMiddleware CSRF保护中间件
func CircuitBreakerMiddleware ¶
func CircuitBreakerMiddleware() gin.HandlerFunc
CircuitBreakerMiddleware 熔断器中间件
func CombinedTimeoutCircuitMiddleware ¶
func CombinedTimeoutCircuitMiddleware() gin.HandlerFunc
CombinedTimeoutCircuitMiddleware 组合超时和熔断中间件。 Respects enableTimeout / enableCircuitBreaker set via InitTimeoutCircuitManager.
func DeprecationHeaders ¶
func DeprecationHeaders(sunset string) gin.HandlerFunc
DeprecationHeaders sets RFC 8594-style Deprecation / Sunset response headers on marked routes. sunset is an HTTP-date or opaque token (e.g. "2027-01-01").
func ErrorHandler ¶
func ErrorHandler() gin.HandlerFunc
ErrorHandler is a Gin middleware that recovers from panics and converts them to structured AppError responses. It also handles any errors stored in the gin.Context via c.Error().
func GetCircuitBreakerStats ¶
func GetCircuitBreakerStats() map[string]interface{}
GetCircuitBreakerStats 获取所有熔断器统计信息
func IPACLDecision ¶
func IPACLDecision(globalBlocked, globalAllowed, routeBlocked, routeAllowed IPList, clientIP string) (allowed bool, reason string)
IPACLDecision evaluates block-first, then allow-if-configured semantics.
func InitRedisRateBackend ¶
func InitTimeoutCircuitManager ¶
func InitTimeoutCircuitManager(timeoutCfg TimeoutConfig, cbCfg CircuitBreakerConfig, enableTimeout, enableCircuitBreaker bool)
InitTimeoutCircuitManager configures the global timeout/circuit manager from app config. Safe to call once at startup; subsequent calls are no-ops (sync.Once).
func InputValidationMiddleware ¶
func InputValidationMiddleware() gin.HandlerFunc
InputValidationMiddleware 输入验证中间件
func LoggerMiddleware ¶
func LoggerMiddleware(log *zap.Logger) gin.HandlerFunc
LoggerMiddleware logs completed HTTP requests (requires RequestIDMiddleware first). log is kept for API compatibility; logging uses logger.*Ctx on the global logger.
func MaintenanceMode ¶
func MaintenanceMode(bypass MaintenanceBypassFunc) gin.HandlerFunc
MaintenanceMode returns 503 for non-probe routes when MAINTENANCE_MODE=true. bypass (optional) lets specific requests (e.g. platform admins) through.
func MarkOperationLogged ¶
MarkOperationLogged records that this HTTP request already wrote an operation log.
func OperationAlreadyLogged ¶
OperationAlreadyLogged reports whether an operation log was written for this request.
func PanicRecovery ¶
func PanicRecovery() gin.HandlerFunc
PanicRecovery logs panics and returns 500.
func RedisAllow ¶
RedisAllow is a minimal fixed-window counter shared across replicas.
func RedisRateEnabled ¶
func RedisRateEnabled() bool
func ReqIDFromGin ¶
ReqIDFromGin is a convenience alias for ginlogger.ReqIDFromGin.
func RequestIDMiddleware ¶
func RequestIDMiddleware() gin.HandlerFunc
RequestIDMiddleware assigns X-Reqid on every HTTP request (reuse inbound header or generate). Must run before LoggerMiddleware and handlers so logger.*Ctx helpers see the id.
func SecurityMiddleware ¶
func SecurityMiddleware(config *SecurityConfig) gin.HandlerFunc
SecurityMiddleware 安全中间件
func SetMaintenanceAllowedPaths ¶
func SetMaintenanceAllowedPaths(paths, prefixes []string)
SetMaintenanceAllowedPaths configures which paths/prefixes stay open during maintenance mode. Pass nil/empty to clear. Must be called before the middleware is first invoked.
func SetSkipAccessLogPaths ¶
func SetSkipAccessLogPaths(paths []string)
SetSkipAccessLogPaths configures which path substrings should skip access logging. Pass nil/empty to clear. Must be called before the middleware is first invoked (not safe to mutate concurrently with request handling).
func URLBlacklistMiddleware ¶ added in v0.1.2
func URLBlacklistMiddleware(bl *URLBlacklist) gin.HandlerFunc
URLBlacklistMiddleware returns a Gin middleware that blocks requests matching any pattern in the blacklist. Blocked requests receive a 403 Forbidden response with a JSON body {"error": "url blocked"}.
The blacklist is checked at request time, so patterns added after the middleware is registered take effect immediately.
func URLBlacklistMiddlewareWithHandler ¶ added in v0.1.2
func URLBlacklistMiddlewareWithHandler(bl *URLBlacklist, handler gin.HandlerFunc) gin.HandlerFunc
URLBlacklistMiddlewareWithHandler is like URLBlacklistMiddleware but allows a custom handler for blocked requests (e.g. for logging or custom error formats).
func WriteError ¶
WriteError is a convenience helper to attach an error to the context and abort.
func XSSProtectionMiddleware ¶
func XSSProtectionMiddleware() gin.HandlerFunc
XSSProtectionMiddleware XSS防护中间件
Types ¶
type Breaker ¶
type Breaker interface {
Allow() error
MarkSuccess()
MarkFailed()
}
Breaker is the circuit-breaker interface used by the timeout/circuit middleware. Both ling-base/circuitbreaker.CircuitBreaker and circuitbreaker.SREBreaker satisfy this interface, so applications can choose the strategy that fits their traffic profile.
type BreakerFactory ¶
BreakerFactory creates a Breaker for a given endpoint key. Used by TimeoutCircuitManager to lazily create per-endpoint breakers.
func DefaultBreakerFactory ¶
func DefaultBreakerFactory(cfg circuitbreaker.Config) BreakerFactory
DefaultBreakerFactory returns a factory that creates circuitbreaker.CircuitBreaker instances with the given config.
func NoopBreakerFactory ¶
func NoopBreakerFactory() BreakerFactory
NoopBreakerFactory returns a factory that creates breakers which never reject. Useful for disabling circuit breaking while keeping the middleware chain intact.
func SREBreakerFactory ¶
func SREBreakerFactory(opts ...circuitbreaker.SREOption) BreakerFactory
SREBreakerFactory returns a factory that creates SRE-style adaptive breakers with the given options.
type CORSConfig ¶
type CORSConfig struct {
// AllowOrigins 允许的来源列表。"*" 表示允许所有。
AllowOrigins []string
// AllowMethods 允许的 HTTP 方法。默认 GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD。
AllowMethods []string
// AllowHeaders 允许的请求头。默认 Content-Type/Authorization/X-Reqid。
AllowHeaders []string
// ExposeHeaders 暴露给浏览器的响应头。
ExposeHeaders []string
// AllowCredentials 是否允许携带凭证(Cookie 等)。
AllowCredentials bool
// MaxAge 预检请求缓存时间(秒)。
MaxAge int
}
CORSConfig 配置 CORS 中间件。
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig 返回默认的 CORS 配置(允许所有来源)。
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker 熔断器
func NewCircuitBreaker ¶
func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker
NewCircuitBreaker 创建新的熔断器
func (*CircuitBreaker) GetState ¶
func (cb *CircuitBreaker) GetState() CircuitBreakerState
GetState 获取熔断器状态
func (*CircuitBreaker) GetStats ¶
func (cb *CircuitBreaker) GetStats() map[string]interface{}
GetStats 获取熔断器统计信息
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
// 失败阈值
FailureThreshold int
// 成功阈值(半开状态下)
SuccessThreshold int
// 超时时间
Timeout time.Duration
// 熔断器打开后的等待时间
OpenTimeout time.Duration
// 最大并发请求数
MaxConcurrentRequests int
}
CircuitBreakerConfig 熔断器配置
func DefaultCircuitBreakerConfig ¶
func DefaultCircuitBreakerConfig() CircuitBreakerConfig
DefaultCircuitBreakerConfig 默认熔断器配置
type CircuitBreakerState ¶
type CircuitBreakerState int
CircuitBreakerState 熔断器状态
const ( StateClosed CircuitBreakerState = iota StateHalfOpen StateOpen )
type IPList ¶
IPList holds parsed IP/CIDR entries for allow/block checks.
func ParseIPList ¶
ParseIPList parses a comma-separated list of IPs and CIDRs. "*" means allow any (used by allowlists only).
type MaintenanceBypassFunc ¶
MaintenanceBypassFunc returns true if the request should bypass maintenance. Apps can plug in their own admin-token check here; nil means no bypass.
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 TimeoutCircuitManager ¶
type TimeoutCircuitManager struct {
// contains filtered or unexported fields
}
TimeoutCircuitManager 超时和熔断管理器
func GetTimeoutCircuitManager ¶
func GetTimeoutCircuitManager() *TimeoutCircuitManager
GetTimeoutCircuitManager 获取全局超时熔断管理器
func NewTimeoutCircuitManager ¶
func NewTimeoutCircuitManager(timeoutConfig TimeoutConfig, cbConfig CircuitBreakerConfig) *TimeoutCircuitManager
NewTimeoutCircuitManager 创建超时和熔断管理器
func (*TimeoutCircuitManager) SetBreakerFactory ¶
func (m *TimeoutCircuitManager) SetBreakerFactory(f BreakerFactory)
SetBreakerFactory overrides the default breaker creation strategy. Pass DefaultBreakerFactory, SREBreakerFactory, or a custom factory. Must be called before the middleware is first invoked.
func (*TimeoutCircuitManager) SetLongLivedPrefixes ¶
func (m *TimeoutCircuitManager) SetLongLivedPrefixes(prefixes []string)
SetLongLivedPrefixes registers additional path prefixes that should skip timeout/circuit wrapping (e.g. WebSocket / SSE / streaming endpoints).
type TimeoutConfig ¶
type TimeoutConfig struct {
// 默认超时时间
DefaultTimeout time.Duration
// 接口级别超时配置
EndpointTimeouts map[string]time.Duration
// 超时后的降级响应
FallbackResponse interface{}
}
TimeoutConfig 超时配置
func DefaultTimeoutConfig ¶
func DefaultTimeoutConfig() TimeoutConfig
DefaultTimeoutConfig 默认超时配置(仅包含探针,应用可自行注入 EndpointTimeouts)
type URLBlacklist ¶ added in v0.1.2
type URLBlacklist struct {
// contains filtered or unexported fields
}
URLBlacklist is a configurable URL blacklist matcher for Gin middleware. It supports exact path matching, wildcard patterns (e.g. "/admin/*"), and path-prefix matching. Patterns are matched against the cleaned request path (with trailing slashes removed and "." / ".." resolved).
Quick start ¶
bl := NewURLBlacklist()
bl.Add("/admin/secret")
bl.Add("/internal/*")
r := gin.New()
r.Use(URLBlacklistMiddleware(bl))
Pattern syntax ¶
- Exact: "/admin/login" matches only that path.
- Wildcard: "/api/*" matches "/api/anything", "/api/a/b", etc. The wildcard matches one or more path segments.
- Prefix: "/private" matches "/private", "/private/x", "/private/a/b". Add a trailing "/" to require at least one extra segment: "/private/" matches "/private/x" but not "/private" itself.
func NewURLBlacklist ¶ added in v0.1.2
func NewURLBlacklist() *URLBlacklist
NewURLBlacklist creates an empty blacklist.
func (*URLBlacklist) Add ¶ added in v0.1.2
func (b *URLBlacklist) Add(pattern string)
Add registers a pattern. Patterns ending with "/*" are treated as wildcards; patterns ending with "/" (but not "/*") are treated as prefixes (matching that string plus anything after); all others are exact matches.
Note: cleanPath strips trailing slashes, so a pattern like "/private/" is preserved as a prefix pattern before cleaning is applied to the base path.
func (*URLBlacklist) AddAll ¶ added in v0.1.2
func (b *URLBlacklist) AddAll(patterns ...string)
AddAll registers multiple patterns.
func (*URLBlacklist) Count ¶ added in v0.1.2
func (b *URLBlacklist) Count() int
Count returns the total number of registered patterns.
func (*URLBlacklist) IsBlocked ¶ added in v0.1.2
func (b *URLBlacklist) IsBlocked(urlPath string) bool
IsBlocked reports whether the given path matches any blacklist pattern.
func (*URLBlacklist) Remove ¶ added in v0.1.2
func (b *URLBlacklist) Remove(pattern string)
Remove unregisters a pattern.