Documentation
¶
Index ¶
- Constants
- Variables
- func CORS() gin.HandlerFunc
- func CORSWithConfig(cfg CORSConfig) gin.HandlerFunc
- func GetClaims(c *gin.Context) (*jwt.Claims, bool)
- func GetTraceID(c *gin.Context) string
- func GetTraceIDWithKey(c *gin.Context, key string) string
- func GetUserID(c *gin.Context) (int64, bool)
- func GetUsername(c *gin.Context) (string, bool)
- func HasRole(c *gin.Context, role string) bool
- func JWT(tokenManager jwt.TokenManager) gin.HandlerFunc
- func JWTWithConfig(tokenManager jwt.TokenManager, config JWTConfig) gin.HandlerFunc
- func RateLimiter(manager *limiter.Manager) gin.HandlerFunc
- func RateLimiterKeyByAPIKey(headerName string) func(*gin.Context) string
- func RateLimiterKeyByIP(c *gin.Context) string
- func RateLimiterKeyByPathAndIP(c *gin.Context) string
- func RateLimiterKeyByUser(userIDKey string) func(*gin.Context) string
- func RateLimiterWithConfig(cfg RateLimiterConfig) gin.HandlerFunc
- func Recovery() gin.HandlerFunc
- func RegisterHealthRoutes(router gin.IRouter, aggregator *health.Aggregator)
- func RequestLog() gin.HandlerFunc
- func RequestLogWithConfig(cfg RequestLogConfig) gin.HandlerFunc
- func TraceID(cfg TraceConfig) gin.HandlerFunc
- type CORSConfig
- type HTTPMetrics
- type HTTPMetricsConfig
- type HealthCheckHandler
- type JWTConfig
- type RateLimiterConfig
- type RequestLogConfig
- type TraceConfig
Constants ¶
const ( // TraceIDKeyDefault TraceID key default value in the Context TraceIDKeyDefault = "trace_id" // The default value for the TraceID key in the TraceIDHeaderDefault HTTP header TraceIDHeaderDefault = "X-Trace-ID" )
Variables ¶
var DefaultJWTConfig = JWTConfig{ Skipper: nil, TokenLookup: "header:Authorization", TokenHeadName: "Bearer", ErrorHandler: defaultJWTErrorHandler, }
Default JWT Configuration
Functions ¶
func CORS ¶
func CORS() gin.HandlerFunc
Create CORS middleware (using default configuration)
Function: - Handle Cross-Origin Resource Sharing (CORS) - Automatically respond to OPTIONS preflight requests - Set CORS related response headers
Usage:
engine.Use(middleware.CORS())
func CORSWithConfig ¶
func CORSWithConfig(cfg CORSConfig) gin.HandlerFunc
CORSWithConfig creates CORS middleware (custom configuration)
func GetTraceID ¶
GetTraceID retrieves the TraceID from gin.Context (convenience method) Use default key
func GetTraceIDWithKey ¶
GetTraceIDWithKey retrieves the TraceID from gin.Context (specified by Key)
func JWT ¶
func JWT(tokenManager jwt.TokenManager) gin.HandlerFunc
Create JWT middleware (using default configuration)
func JWTWithConfig ¶
func JWTWithConfig(tokenManager jwt.TokenManager, config JWTConfig) gin.HandlerFunc
Create JWT middleware with custom configuration
func RateLimiter ¶
func RateLimiter(manager *limiter.Manager) gin.HandlerFunc
Create rate limiting middleware
Function: 1. Rate limiting for requests Supports multiple rate limiting algorithms (Token Bucket, Sliding Window, Concurrency, Adaptive) Supports rate limiting by dimensions such as path, IP, user etc. English: Automatically allow when rate limiter is not enabled English: Downgrade and proceed in case of rate limiter error
Usage:
// Basic usage
engine.Use(middleware.RateLimiter(limiterManager))
// Custom configuration
cfg := middleware.DefaultRateLimiterConfig(limiterManager)
cfg.KeyFunc = middleware.RateLimiterKeyByIP
cfg.SkipPaths = []string{"/health", "/metrics"}
engine.Use(middleware.RateLimiterWithConfig(cfg))
func RateLimiterKeyByAPIKey ¶
RateLimiterKeyByAPIKey generates resource keys based on API key Used for rate limiting by API key (requires obtaining from Header or Query)
Usage:
cfg.KeyFunc = middleware.RateLimiterKeyByAPIKey("X-API-Key")
func RateLimiterKeyByIP ¶
RateLimiterKeyByIP generates resource keys based on client IP Used for IP rate limiting
func RateLimiterKeyByPathAndIP ¶
RateLimiterKeyByPathAndIP generates a resource key based on path and IP For rate limiting by path+IP combination
func RateLimiterKeyByUser ¶
RateLimiterKeyByUser generates resource keys based on user ID For rate limiting by user (requires obtaining user information from context)
Usage:
cfg.KeyFunc = middleware.RateLimiterKeyByUser("user_id")
func RateLimiterWithConfig ¶
func RateLimiterWithConfig(cfg RateLimiterConfig) gin.HandlerFunc
Creates a rate limiter middleware with custom configuration
func Recovery ¶
func Recovery() gin.HandlerFunc
Recovery from Gin panic (structured logging) Replace gin.Recovery() with a custom Logger component to log panic logs Function: - Catch panics in the handler to prevent program crashes - Log complete stack information - Return a unified 500 error response to the client - Do not expose sensitive stack information to clients
func RegisterHealthRoutes ¶
func RegisterHealthRoutes(router gin.IRouter, aggregator *health.Aggregator)
RegisterHealthRoutes Register health check routes Convenient method, automatically registers all health check endpoints
func RequestLog ¶
func RequestLog() gin.HandlerFunc
RequestLog Gin HTTP request logging middleware (structured logs) Replace gin.Logger() with a custom Logger component to log request logs
Function: - Structured log fields (status code, duration, client IP, etc.) - Automatically classify by status code (500+ Error, 400+ Warning, 200+ Information) - Record request error information - Support for automatic association of TraceID (using Context API) - Support skipping specified paths
Usage:
engine.Use(middleware.RequestLog())
// or custom configuration
cfg := middleware.DefaultRequestLogConfig()
cfg.SkipPaths = []string{"/health", "/metrics"}
engine.Use(middleware.RequestLogWithConfig(cfg))
func RequestLogWithConfig ¶
func RequestLogWithConfig(cfg RequestLogConfig) gin.HandlerFunc
Create HTTP request log middleware with custom configuration
func TraceID ¶
func TraceID(cfg TraceConfig) gin.HandlerFunc
Create TraceID middleware
Function: 1. Extract or generate TraceID from Header Inject into gin.Context and context.Context Optional: Write TraceID to Response Header 4. 🎯 Intelligent switch: If OpenTelemetry is enabled, prioritize using the OTel Trace ID
Usage:
engine.Use(middleware.TraceID(middleware.DefaultTraceConfig()))
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// AllowOrigins list of allowed sources (default ["*"])
// Example: ["https://example.com", "https://app.example.com"]
AllowOrigins []string
// AllowMethods list of allowed HTTP methods (default ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
AllowMethods []string
// AllowHeaders list of allowed request headers (default ["Origin", "Content-Type", "Accept", "Authorization"])
AllowHeaders []string
// ExposeHeaders list of response headers exposed to the client (default [])
ExposeHeaders []string
// AllowCredentials whether to allow sending credentials (such as Cookies, HTTP authentication, etc.) (default false)
// Note: When set to true, AllowOrigins cannot use "*"
AllowCredentials bool
// MaxAge preflight request cache time (seconds) (default 43200, i.e., 12 hours)
MaxAge int
}
CORSConfig CORS middleware configuration
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig default CORS configuration
type HTTPMetrics ¶
type HTTPMetrics struct {
// contains filtered or unexported fields
}
HTTPMetrics HTTP layer metric collector Implements component.MetricsProvider interface
func NewHTTPMetrics ¶
func NewHTTPMetrics(cfg HTTPMetricsConfig) *HTTPMetrics
Create new HTTP metrics collector
func (*HTTPMetrics) Handler ¶
func (m *HTTPMetrics) Handler() gin.HandlerFunc
Handler returns a Gin middleware for collecting HTTP metrics. Metrics must be registered via RegisterMetrics before calling this.
func (*HTTPMetrics) IsMetricsEnabled ¶
func (m *HTTPMetrics) IsMetricsEnabled() bool
IsMetricsEnabled returns whether metrics collection is enabled
func (*HTTPMetrics) IsRegistered ¶
func (m *HTTPMetrics) IsRegistered() bool
IsRegistered returns whether metrics have been registered
func (*HTTPMetrics) MetricsName ¶
func (m *HTTPMetrics) MetricsName() string
MetricsName returns the metrics group name
func (*HTTPMetrics) RegisterMetrics ¶
func (m *HTTPMetrics) RegisterMetrics(meter metric.Meter) error
RegisterMetrics registers all HTTP metrics with the provided Meter
type HTTPMetricsConfig ¶
HTTP Metrics Config HTTP metric configuration
type HealthCheckHandler ¶
type HealthCheckHandler struct {
// contains filtered or unexported fields
}
HealthCheckHandler health check HTTP handler Provide a unified health check endpoint
func NewHealthCheckHandler ¶
func NewHealthCheckHandler(aggregator *health.Aggregator) *HealthCheckHandler
Create new health check handler
func (*HealthCheckHandler) Handle ¶
func (h *HealthCheckHandler) Handle() gin.HandlerFunc
Handle health check request GET /health - Full health check GET /health/liveness - Liveness probe (K8s liveness probe) GET /health/readiness - Readiness probe (K8s readiness probe)
func (*HealthCheckHandler) HandleLiveness ¶
func (h *HealthCheckHandler) HandleLiveness() gin.HandlerFunc
HandleLiveness K8s Liveness Probe A simple check to see if the application is alive (does not check dependencies)
func (*HealthCheckHandler) HandleReadiness ¶
func (h *HealthCheckHandler) HandleReadiness() gin.HandlerFunc
HandleReadiness K8s Readiness Probe Check if the application is ready (including all dependencies)
type JWTConfig ¶
type JWTConfig struct {
// Skip function for middleware
Skipper func(*gin.Context) bool
// Token lookup position (format: header:Authorization)
TokenLookup string
// TokenHeadName Token prefix (such as "Bearer")
TokenHeadName string
// Error handler function
ErrorHandler func(*gin.Context, error)
}
JWTConfig JWT middleware configuration
type RateLimiterConfig ¶
type RateLimiterConfig struct {
// Manager Rate Limiter Manager (required)
Manager *limiter.Manager
// KeyFunc custom resource key generation function (default: method:path)
KeyFunc func(*gin.Context) string
// ErrorHandler custom error handling function (default: log errors but proceed)
ErrorHandler func(*gin.Context, error)
// RateLimitHandler custom rate limiting response function (default: return 429)
RateLimitHandler func(*gin.Context)
// SkipFunc optional function to skip rate limiting conditions
SkipFunc func(*gin.Context) bool
// SkipPaths list of paths to bypass rate limiting (optional)
SkipPaths []string
}
RateLimiterConfig rate limiting middleware configuration
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig(manager *limiter.Manager) RateLimiterConfig
DefaultRateLimiterConfig default rate limiting configuration
type RequestLogConfig ¶
type RequestLogConfig struct {
// SkipPaths list of paths to skip recording
SkipPaths []string
// EnableBody Whether to log request body (considering performance, default is false)
EnableBody bool
// MaxBodySize maximum request body recording size (bytes)
MaxBodySize int
}
HTTP request log configuration
func DefaultRequestLogConfig ¶
func DefaultRequestLogConfig() RequestLogConfig
Default request log configuration
type TraceConfig ¶
type TraceConfig struct {
// TraceIDKey stored in Context (default "trace_id")
TraceIDKey string
// TraceIDHeader is the key in the HTTP Header (default "X-Trace-ID")
TraceIDHeader string
// EnableResponseHeader whether to write TraceID into Response Header (default true)
EnableResponseHeader bool
// Generator custom TraceID generator (default uses UUID)
Generator func() string
}
TraceConfig Trace middleware configuration
func DefaultTraceConfig ¶
func DefaultTraceConfig() TraceConfig
Default configuration for DefaultTraceConfig