middleware

package
v0.0.0-...-ee5b157 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2025 License: AGPL-3.0 Imports: 20 Imported by: 0

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

View Source
const UserContextKey = "user"

UserContextKey is the key used to store user in request context.

Variables

This section is empty.

Functions

func AbortWithAuthenticationError

func AbortWithAuthenticationError(c *gin.Context, code, message string)

AbortWithAuthenticationError aborts the request with an authentication error.

func AbortWithAuthorizationError

func AbortWithAuthorizationError(c *gin.Context, code, message string)

AbortWithAuthorizationError aborts the request with an authorization error.

func AbortWithConflictError

func AbortWithConflictError(c *gin.Context, code, message string)

AbortWithConflictError aborts the request with a conflict error.

func AbortWithError

func AbortWithError(c *gin.Context, err *domain.Error)

AbortWithError aborts the request with a domain error.

func AbortWithInternalError

func AbortWithInternalError(c *gin.Context, code, message string, cause error)

AbortWithInternalError aborts the request with an internal error.

func AbortWithNotFoundError

func AbortWithNotFoundError(c *gin.Context, code, message string)

AbortWithNotFoundError aborts the request with a not found error.

func AbortWithValidationError

func AbortWithValidationError(c *gin.Context, code, message string, details map[string]interface{})

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

func GetRequestID(c *gin.Context) string

GetRequestID extracts request ID from Gin context.

func GetRequestIDFromContext

func GetRequestIDFromContext(ctx context.Context) string

GetRequestIDFromContext extracts request ID from standard context.

func GetUserFromContext

func GetUserFromContext(c *gin.Context) (*domain.User, bool)

GetUserFromContext extracts the authenticated user from Gin context.

func GetUserFromRequestContext

func GetUserFromRequestContext(ctx context.Context) (*domain.User, bool)

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

func ValidateJSON[T any](c *gin.Context, target *T) bool

ValidateJSON validates JSON request body against a struct.

func ValidateQuery

func ValidateQuery[T any](c *gin.Context, target *T) bool

ValidateQuery validates query parameters against a struct.

func ValidateURI

func ValidateURI[T any](c *gin.Context, target *T) bool

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

func NewLRUCache(capacity int) *LRUCache

NewLRUCache creates a new LRU cache with the specified capacity.

func (*LRUCache) Clear

func (c *LRUCache) Clear()

Clear removes all items from the cache.

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.

func (*LRUCache) Len

func (c *LRUCache) Len() int

Len returns the current number of items in the cache.

type LRUItem

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

LRUItem represents an item in the LRU cache.

type LoggingConfig

type LoggingConfig struct {
	Output     io.Writer
	TimeFormat string
	SkipPaths  []string
}

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) Allow

func (rm *RateLimitManager) Allow(ctx context.Context, key string) (bool, error)

Allow checks if a request should be allowed for the given key.

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.

func (*RedisRateLimiter) Allow

func (rl *RedisRateLimiter) Allow(ctx context.Context, key string) (bool, error)

Allow checks if a request should be allowed using Redis sliding window.

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.

Jump to

Keyboard shortcuts

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