Documentation
¶
Overview ¶
Package middleware provides HTTP middleware functions for authentication and authorization.
Package middleware provides HTTP middleware functions.
Package middleware provides HTTP middleware functions.
Package middleware provides HTTP middleware functions.
Package middleware provides HTTP middleware functions.
Package middleware provides HTTP middleware functions.
Package middleware provides HTTP middleware functions.
Package middleware provides HTTP middleware functions.
Package middleware provides HTTP middleware functions.
Index ¶
- Constants
- func AbortWithAuthenticationError(c *gin.Context, code, message string)
- func AbortWithAuthorizationError(c *gin.Context, code, message string)
- func AbortWithConflictError(c *gin.Context, code, message string)
- func AbortWithError(c *gin.Context, err *domain.Error)
- func AbortWithInternalError(c *gin.Context, code, message string, cause error)
- func AbortWithNotFoundError(c *gin.Context, code, message string)
- func AbortWithValidationError(c *gin.Context, code, message string, details map[string]interface{})
- func CORSMiddleware(allowedOrigins []string, allowedMethods []string, allowedHeaders []string, ...) gin.HandlerFunc
- func DefaultCORSMiddleware() gin.HandlerFunc
- func DefaultErrorHandlerMiddleware() gin.HandlerFunc
- func DefaultLoggingMiddleware() gin.HandlerFunc
- func DefaultRateLimitMiddleware(requestsPerMinute int) gin.HandlerFunc
- func DefaultRecoveryMiddleware() gin.HandlerFunc
- func DevelopmentErrorHandlerMiddleware() gin.HandlerFunc
- func DevelopmentRecoveryMiddleware() gin.HandlerFunc
- func ErrorHandlerMiddleware(config ErrorHandlerConfig) gin.HandlerFunc
- func GetRequestID(c *gin.Context) string
- func GetRequestIDFromContext(ctx context.Context) string
- func GetUserFromContext(c *gin.Context) (*domain.User, bool)
- func GetUserFromRequestContext(ctx context.Context) (*domain.User, bool)
- func LoggingMiddleware(config LoggingConfig) gin.HandlerFunc
- func ProductionCORSMiddleware(allowedOrigins []string) gin.HandlerFunc
- func ProductionRecoveryMiddleware() gin.HandlerFunc
- func RecoveryMiddleware(config RecoveryConfig) gin.HandlerFunc
- func RequestIDMiddleware() gin.HandlerFunc
- func StructuredLoggingMiddleware() gin.HandlerFunc
- func UserBasedRateLimitMiddleware(requestsPerMinute int) gin.HandlerFunc
- func ValidateJSON[T any](c *gin.Context, target *T) bool
- func ValidateQuery[T any](c *gin.Context, target *T) bool
- func ValidateURI[T any](c *gin.Context, target *T) bool
- func ValidationMiddleware() gin.HandlerFunc
- type AuthMiddleware
- func (m *AuthMiddleware) OptionalAuth() gin.HandlerFunc
- func (m *AuthMiddleware) RequireAdmin() gin.HandlerFunc
- func (m *AuthMiddleware) RequireAuth() gin.HandlerFunc
- func (m *AuthMiddleware) RequireOwnership(extractOwnerID func(c *gin.Context) string) gin.HandlerFunc
- func (m *AuthMiddleware) RequireRole(role domain.UserRole) gin.HandlerFunc
- type ErrorHandlerConfig
- type LRUCache
- type LRUItem
- type LoggingConfig
- type RateLimitConfig
- type RateLimitManager
- type RateLimitStats
- type RateLimiter
- type RecoveryConfig
- type RedisRateLimiter
- type RequestIDKeyType
Constants ¶
const UserContextKey = "user"
UserContextKey is the key used to store user in request context.
Variables ¶
This section is empty.
Functions ¶
func AbortWithAuthenticationError ¶
AbortWithAuthenticationError aborts the request with an authentication error.
func AbortWithAuthorizationError ¶
AbortWithAuthorizationError aborts the request with an authorization error.
func AbortWithConflictError ¶
AbortWithConflictError aborts the request with a conflict error.
func AbortWithError ¶
AbortWithError aborts the request with a domain error.
func AbortWithInternalError ¶
AbortWithInternalError aborts the request with an internal error.
func AbortWithNotFoundError ¶
AbortWithNotFoundError aborts the request with a not found error.
func AbortWithValidationError ¶
AbortWithValidationError aborts the request with a validation error.
func CORSMiddleware ¶
func CORSMiddleware( allowedOrigins []string, allowedMethods []string, allowedHeaders []string, allowCredentials bool, ) gin.HandlerFunc
CORSMiddleware returns a CORS middleware with configurable options.
func DefaultCORSMiddleware ¶
func DefaultCORSMiddleware() gin.HandlerFunc
DefaultCORSMiddleware returns a CORS middleware with sensible defaults for development.
func DefaultErrorHandlerMiddleware ¶
func DefaultErrorHandlerMiddleware() gin.HandlerFunc
DefaultErrorHandlerMiddleware returns an error handler with sensible defaults.
func DefaultLoggingMiddleware ¶
func DefaultLoggingMiddleware() gin.HandlerFunc
DefaultLoggingMiddleware returns a logging middleware with sensible defaults.
func DefaultRateLimitMiddleware ¶
func DefaultRateLimitMiddleware(requestsPerMinute int) gin.HandlerFunc
DefaultRateLimitMiddleware returns a rate limiting middleware with IP-based limiting. Note: This creates a rate limiter without proper cleanup. Use RateLimitMiddleware directly for production.
func DefaultRecoveryMiddleware ¶
func DefaultRecoveryMiddleware() gin.HandlerFunc
DefaultRecoveryMiddleware returns a recovery middleware with sensible defaults for production.
func DevelopmentErrorHandlerMiddleware ¶
func DevelopmentErrorHandlerMiddleware() gin.HandlerFunc
DevelopmentErrorHandlerMiddleware returns an error handler for development.
func DevelopmentRecoveryMiddleware ¶
func DevelopmentRecoveryMiddleware() gin.HandlerFunc
DevelopmentRecoveryMiddleware returns a recovery middleware configured for development.
func ErrorHandlerMiddleware ¶
func ErrorHandlerMiddleware(config ErrorHandlerConfig) gin.HandlerFunc
ErrorHandlerMiddleware returns a middleware that handles errors consistently.
func GetRequestID ¶
GetRequestID extracts request ID from Gin context.
func GetRequestIDFromContext ¶
GetRequestIDFromContext extracts request ID from standard context.
func GetUserFromContext ¶
GetUserFromContext extracts the authenticated user from Gin context.
func GetUserFromRequestContext ¶
GetUserFromRequestContext extracts the authenticated user from request context.
func LoggingMiddleware ¶
func LoggingMiddleware(config LoggingConfig) gin.HandlerFunc
LoggingMiddleware returns a logging middleware with custom configuration.
func ProductionCORSMiddleware ¶
func ProductionCORSMiddleware(allowedOrigins []string) gin.HandlerFunc
ProductionCORSMiddleware returns a CORS middleware configured for production use.
func ProductionRecoveryMiddleware ¶
func ProductionRecoveryMiddleware() gin.HandlerFunc
ProductionRecoveryMiddleware returns a recovery middleware configured for production.
func RecoveryMiddleware ¶
func RecoveryMiddleware(config RecoveryConfig) gin.HandlerFunc
RecoveryMiddleware returns a panic recovery middleware with custom configuration.
func RequestIDMiddleware ¶
func RequestIDMiddleware() gin.HandlerFunc
RequestIDMiddleware adds a unique request ID to each request.
func StructuredLoggingMiddleware ¶
func StructuredLoggingMiddleware() gin.HandlerFunc
StructuredLoggingMiddleware returns a middleware that logs in structured JSON format.
func UserBasedRateLimitMiddleware ¶
func UserBasedRateLimitMiddleware(requestsPerMinute int) gin.HandlerFunc
UserBasedRateLimitMiddleware returns a rate limiting middleware based on authenticated user. Note: This creates a rate limiter without proper cleanup. Use RateLimitMiddleware directly for production.
func ValidateJSON ¶
ValidateJSON validates JSON request body against a struct.
func ValidateQuery ¶
ValidateQuery validates query parameters against a struct.
func ValidateURI ¶
ValidateURI validates URI parameters against a struct.
func ValidationMiddleware ¶
func ValidationMiddleware() gin.HandlerFunc
ValidationMiddleware returns a middleware that validates request bodies.
Types ¶
type AuthMiddleware ¶
type AuthMiddleware struct {
// contains filtered or unexported fields
}
AuthMiddleware provides authentication middleware functionality.
func NewAuthMiddleware ¶
func NewAuthMiddleware(authService services.AuthService) *AuthMiddleware
NewAuthMiddleware creates a new authentication middleware.
func (*AuthMiddleware) OptionalAuth ¶
func (m *AuthMiddleware) OptionalAuth() gin.HandlerFunc
OptionalAuth middleware that extracts user if token is provided but doesn't require it.
func (*AuthMiddleware) RequireAdmin ¶
func (m *AuthMiddleware) RequireAdmin() gin.HandlerFunc
RequireAdmin middleware that requires admin role.
func (*AuthMiddleware) RequireAuth ¶
func (m *AuthMiddleware) RequireAuth() gin.HandlerFunc
RequireAuth middleware that requires valid JWT authentication.
func (*AuthMiddleware) RequireOwnership ¶
func (m *AuthMiddleware) RequireOwnership(extractOwnerID func(c *gin.Context) string) gin.HandlerFunc
RequireOwnership middleware that requires user to be the owner of a resource.
func (*AuthMiddleware) RequireRole ¶
func (m *AuthMiddleware) RequireRole(role domain.UserRole) gin.HandlerFunc
RequireRole middleware that requires a specific role.
type ErrorHandlerConfig ¶
type ErrorHandlerConfig struct { // CustomErrorHandler allows for custom error handling logic CustomErrorHandler func(c *gin.Context, err error) // IncludeStackTrace determines whether to include stack traces in error responses IncludeStackTrace bool // LogErrors determines whether errors should be logged LogErrors bool }
ErrorHandlerConfig holds configuration for error handling middleware.
type LRUCache ¶
type LRUCache struct {
// contains filtered or unexported fields
}
LRUCache represents an LRU cache for rate limiters.
func NewLRUCache ¶
NewLRUCache creates a new LRU cache with the specified capacity.
func (*LRUCache) Get ¶
func (c *LRUCache) Get(key string, factory func() *RateLimiter) *RateLimiter
Get retrieves a rate limiter from the cache or creates a new one.
type LRUItem ¶
type LRUItem struct {
// contains filtered or unexported fields
}
LRUItem represents an item in the LRU cache.
type LoggingConfig ¶
LoggingConfig holds configuration for the logging middleware.
type RateLimitConfig ¶
type RateLimitConfig struct { // KeyGenerator is a function that generates a key for rate limiting (e.g., IP address, user ID). KeyGenerator func(c *gin.Context) string // OnExceeded is called when rate limit is exceeded. OnExceeded func(c *gin.Context) // RedisAddr specifies the Redis server address (required if UseRedis is true). RedisAddr string // RedisPassword specifies the Redis password (optional). RedisPassword string // CleanupInterval specifies how often to clean up old limiters (default: 5 minutes). CleanupInterval time.Duration // MaxAge specifies the maximum age of an inactive limiter before cleanup (default: 10 minutes). MaxAge time.Duration // RequestsPerMinute specifies the maximum number of requests per minute. RequestsPerMinute int // CacheCapacity specifies the maximum number of rate limiters to keep in memory (default: 10000). // Using LRU cache prevents unbounded memory growth. CacheCapacity int // RedisDB specifies the Redis database number (default: 0). RedisDB int // UseRedis enables Redis-based distributed rate limiting for production environments. UseRedis bool }
RateLimitConfig holds configuration for rate limiting.
type RateLimitManager ¶
type RateLimitManager struct {
// contains filtered or unexported fields
}
RateLimitManager manages rate limiters and their lifecycle.
func NewRateLimitManager ¶
func NewRateLimitManager(ctx context.Context, config RateLimitConfig) *RateLimitManager
NewRateLimitManager creates a new rate limit manager.
func RateLimitMiddleware ¶
func RateLimitMiddleware(ctx context.Context, config RateLimitConfig) (gin.HandlerFunc, *RateLimitManager)
RateLimitMiddleware returns a rate limiting middleware. Important: The returned manager must be shut down gracefully to prevent goroutine leaks.
func (*RateLimitManager) GetLimiter ¶
func (rm *RateLimitManager) GetLimiter(key string) *RateLimiter
GetLimiter gets or creates a rate limiter for the given key (in-memory only).
func (*RateLimitManager) Shutdown ¶
func (rm *RateLimitManager) Shutdown()
Shutdown gracefully shuts down the rate limit manager.
func (*RateLimitManager) Stats ¶
func (rm *RateLimitManager) Stats() RateLimitStats
Stats returns statistics about the rate limiter cache.
type RateLimitStats ¶
type RateLimitStats struct { CacheSize int `json:"cache_size"` CacheCapacity int `json:"cache_capacity"` CacheUsage float64 `json:"cache_usage"` }
RateLimitStats holds statistics about rate limiting.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter represents a simple rate limiter using token bucket algorithm.
func NewRateLimiter ¶
func NewRateLimiter(capacity int, refillRate time.Duration) *RateLimiter
NewRateLimiter creates a new rate limiter.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow() bool
Allow checks if a request should be allowed based on rate limits.
type RecoveryConfig ¶
type RecoveryConfig struct { // HandleRecovery is a custom function to handle panic recovery. // If nil, the default handler will be used. HandleRecovery func(c *gin.Context, err interface{}) // PrintStack determines whether to print stack trace to logs. PrintStack bool // IncludeStackInResponse determines whether to include stack trace in error response (dev only). IncludeStackInResponse bool }
RecoveryConfig holds configuration for the recovery middleware.
type RedisRateLimiter ¶
type RedisRateLimiter struct {
// contains filtered or unexported fields
}
RedisRateLimiter implements distributed rate limiting using Redis.
func NewRedisRateLimiter ¶
func NewRedisRateLimiter(client *redis.Client, keyPrefix string, requestsPerMinute int) *RedisRateLimiter
NewRedisRateLimiter creates a new Redis-based rate limiter.
type RequestIDKeyType ¶
type RequestIDKeyType string
RequestIDKeyType is the type used for request ID context key.
const RequestIDKey RequestIDKeyType = "request_id"
RequestIDKey is the key used to store request ID in context.