Documentation
¶
Index ¶
- Constants
- Variables
- func AsError(err error, target interface{}) bool
- func BadRequest(c *gin.Context, code, message string, details map[string]interface{})
- func Created(c *gin.Context, data interface{}, meta *ResponseMeta)
- func Error(c *gin.Context, statusCode int, code, message string, ...)
- func Forbidden(c *gin.Context, code, message string, details map[string]interface{})
- func GetOrganizationID(c *gin.Context) (string, bool)
- func GetStatusCode(err error) int
- func GetSubjectID(c *gin.Context) (string, bool)
- func GetTraceID(c *gin.Context) string
- func GetUserRoles(c *gin.Context) ([]string, bool)
- func InternalServerError(c *gin.Context, code, message string, details map[string]interface{})
- func IsAdmin(c *gin.Context) bool
- func IsError(err error, target error) bool
- func NotFound(c *gin.Context, code, message string, details map[string]interface{})
- func Retry(ctx context.Context, config *RetryConfig, operation RetryableOperation) error
- func RetryWithResult[T any](ctx context.Context, config *RetryConfig, ...) (T, error)
- func Success(c *gin.Context, data interface{}, meta *ResponseMeta)
- func Unauthorized(c *gin.Context, code, message string, details map[string]interface{})
- type AppError
- func IsAppError(err error) (*AppError, bool)
- func NewAppError(code ErrorCode, message string, statusCode int) *AppError
- func NewBusinessRuleError(rule string, details string) *AppError
- func NewDatabaseError(operation string, cause error) *AppError
- func NewETagMismatchError(expected, actual string) *AppError
- func NewExternalServiceError(service string, cause error) *AppError
- func NewForbiddenError(message string) *AppError
- func NewIdempotencyConflictError(message string) *AppError
- func NewInternalError(message string) *AppError
- func NewNotFoundError(resource string) *AppError
- func NewOptimisticLockConflictError(message string) *AppError
- func NewPreconditionFailedError(message string) *AppError
- func NewUnauthorizedError(message string) *AppError
- func NewValidationError(message string) *AppError
- func NewVersionConflictError(expected, actual int64) *AppError
- func WrapError(err error, code ErrorCode, message string, statusCode int) *AppError
- type CircuitBreaker
- type CircuitBreakerConfig
- type CircuitBreakerState
- type ConflictError
- type DefaultLogger
- type ErrorCode
- type ErrorHandler
- func (h *ErrorHandler) ErrorMiddleware() gin.HandlerFunc
- func (h *ErrorHandler) HandleError(c *gin.Context, err error)
- func (h *ErrorHandler) HandlePanic(c *gin.Context, recovered interface{})
- func (h *ErrorHandler) HandleValidationError(c *gin.Context, validationErr *ValidationErrors)
- func (h *ErrorHandler) RecoveryMiddleware() gin.HandlerFunc
- type ErrorWithContext
- type FilterParams
- type IdempotencyManager
- type Logger
- type OptimisticLockError
- type OptimisticLockManager
- func (m *OptimisticLockManager) ExtractETagFromContext(c *gin.Context) (string, bool)
- func (m *OptimisticLockManager) ExtractVersionFromContext(c *gin.Context) (int64, bool)
- func (m *OptimisticLockManager) PrepareForUpdate(entity VersionedEntity)
- func (m *OptimisticLockManager) ValidateETag(entity VersionedEntity, expectedETag, currentETag string) error
- func (m *OptimisticLockManager) ValidateVersion(entity VersionedEntity, expectedVersion int64) error
- type PaginationMeta
- type PaginationParams
- type PaginationRequest
- type Response
- type ResponseError
- type ResponseMeta
- type RetryConfig
- type RetryableOperation
- type SortParams
- type ValidationErrors
- type VersionedEntity
Constants ¶
const ( // DefaultPage is the default page number DefaultPage = 1 // DefaultLimit is the default number of items per page DefaultLimit = 20 // MaxLimit is the maximum number of items per page MaxLimit = 100 )
Variables ¶
var ( // Authentication errors ErrMissingAuthorizationHeader = errors.New("missing authorization header") ErrInvalidAuthorizationFormat = errors.New("invalid authorization format, expected 'Bearer <token>'") ErrEmptyToken = errors.New("empty token") ErrMissingToken = errors.New("missing token") ErrInvalidToken = errors.New("invalid token") ErrTokenExpired = errors.New("token expired") // Authorization errors ErrForbidden = errors.New("forbidden") ErrInsufficientPermissions = errors.New("insufficient permissions") ErrResourceNotFound = errors.New("resource not found") ErrResourceAccessDenied = errors.New("resource access denied") // Validation errors ErrInvalidInput = errors.New("invalid input") ErrMissingRequiredField = errors.New("missing required field") ErrInvalidFormat = errors.New("invalid format") // Database errors ErrDatabaseConnection = errors.New("database connection failed") ErrDatabaseQuery = errors.New("database query failed") ErrDatabaseTransaction = errors.New("database transaction failed") ErrRecordNotFound = errors.New("record not found") ErrDuplicateRecord = errors.New("duplicate record") // Business logic errors ErrInsufficientInventory = errors.New("insufficient inventory") ErrInvalidOrderStatus = errors.New("invalid order status") ErrInvalidPrice = errors.New("invalid price") ErrInvalidQuantity = errors.New("invalid quantity") // External service errors ErrExternalServiceTimeout = errors.New("external service timeout") ErrExternalServiceError = errors.New("external service error") )
Common error definitions
Functions ¶
func BadRequest ¶
BadRequest sends a 400 Bad Request response
func Created ¶
func Created(c *gin.Context, data interface{}, meta *ResponseMeta)
Created sends a 201 Created response
func GetOrganizationID ¶
GetOrganizationID extracts the organization ID from the gin context It tries multiple key variants to ensure compatibility across all handlers
func GetStatusCode ¶
GetStatusCode extracts HTTP status code from error
func GetSubjectID ¶
GetSubjectID extracts the subject ID (user ID) from the gin context It tries multiple key variants to ensure compatibility
func GetTraceID ¶
GetTraceID extracts the trace ID from the gin context
func GetUserRoles ¶
GetUserRoles retrieves the user roles from the gin context
func InternalServerError ¶
InternalServerError sends a 500 Internal Server Error response
func Retry ¶
func Retry(ctx context.Context, config *RetryConfig, operation RetryableOperation) error
Retry executes an operation with retry logic
func RetryWithResult ¶
func RetryWithResult[T any](ctx context.Context, config *RetryConfig, operation func(ctx context.Context, attempt int) (T, error)) (T, error)
RetryWithResult executes an operation with retry logic and returns a result
func Success ¶
func Success(c *gin.Context, data interface{}, meta *ResponseMeta)
Success sends a successful response
Types ¶
type AppError ¶
type AppError struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
Fields map[string]string `json:"fields,omitempty"`
Context map[string]interface{} `json:"context,omitempty"`
Cause error `json:"-"`
StatusCode int `json:"-"`
}
AppError represents a structured application error
func IsAppError ¶
IsAppError checks if an error is an AppError
func NewAppError ¶
NewAppError creates a new AppError
func NewBusinessRuleError ¶
NewBusinessRuleError creates a business rule violation error
func NewDatabaseError ¶
NewDatabaseError creates a database error
func NewETagMismatchError ¶
NewETagMismatchError creates an ETag mismatch error
func NewExternalServiceError ¶
NewExternalServiceError creates an external service error
func NewForbiddenError ¶
NewForbiddenError creates a forbidden error
func NewIdempotencyConflictError ¶
NewIdempotencyConflictError creates an idempotency conflict error
func NewInternalError ¶
NewInternalError creates an internal server error
func NewNotFoundError ¶
NewNotFoundError creates a not found error
func NewOptimisticLockConflictError ¶
NewOptimisticLockConflictError creates an optimistic locking conflict error
func NewPreconditionFailedError ¶
NewPreconditionFailedError creates a precondition failed error
func NewUnauthorizedError ¶
NewUnauthorizedError creates an unauthorized error
func NewValidationError ¶
NewValidationError creates a validation error
func NewVersionConflictError ¶
NewVersionConflictError creates a version conflict error
func (*AppError) WithContext ¶
WithContext adds context to an AppError
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the circuit breaker pattern
func NewCircuitBreaker ¶
func NewCircuitBreaker(config *CircuitBreakerConfig) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker
func (*CircuitBreaker) Execute ¶
func (cb *CircuitBreaker) Execute(ctx context.Context, operation RetryableOperation) error
Execute executes an operation through the circuit breaker
func (*CircuitBreaker) GetState ¶
func (cb *CircuitBreaker) GetState() CircuitBreakerState
GetState returns the current state of the circuit breaker
func (*CircuitBreaker) Reset ¶
func (cb *CircuitBreaker) Reset()
Reset resets the circuit breaker to closed state
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
FailureThreshold int `json:"failure_threshold"`
RecoveryTimeout time.Duration `json:"recovery_timeout"`
MaxRequests int `json:"max_requests"`
}
CircuitBreakerConfig defines circuit breaker behavior
type CircuitBreakerState ¶
type CircuitBreakerState int
CircuitBreakerState represents the state of a circuit breaker
const ( CircuitBreakerClosed CircuitBreakerState = iota CircuitBreakerOpen CircuitBreakerHalfOpen )
type ConflictError ¶
type ConflictError struct {
Type string `json:"type"` // "idempotency" or "optimistic_lock"
Message string `json:"message"`
Details map[string]interface{} `json:"details"`
}
ConflictError represents a conflict error for idempotency or optimistic locking
func (*ConflictError) Error ¶
func (e *ConflictError) Error() string
func (*ConflictError) ToAppError ¶
func (e *ConflictError) ToAppError() *AppError
ToAppError converts ConflictError to AppError
type DefaultLogger ¶
type DefaultLogger struct{}
DefaultLogger implements Logger using standard log package
func (*DefaultLogger) Error ¶
func (l *DefaultLogger) Error(msg string, fields ...interface{})
func (*DefaultLogger) Info ¶
func (l *DefaultLogger) Info(msg string, fields ...interface{})
func (*DefaultLogger) Warn ¶
func (l *DefaultLogger) Warn(msg string, fields ...interface{})
type ErrorCode ¶
type ErrorCode string
ErrorCode represents standardized error codes
const ( // Authentication error codes ErrorCodeMissingAuth ErrorCode = "MISSING_AUTH" ErrorCodeInvalidAuth ErrorCode = "INVALID_AUTH" ErrorCodeTokenExpired ErrorCode = "TOKEN_EXPIRED" // Authorization error codes ErrorCodeForbidden ErrorCode = "FORBIDDEN" ErrorCodeInsufficientPerms ErrorCode = "INSUFFICIENT_PERMISSIONS" ErrorCodeResourceNotFound ErrorCode = "RESOURCE_NOT_FOUND" ErrorCodeAccessDenied ErrorCode = "ACCESS_DENIED" // Validation error codes ErrorCodeInvalidInput ErrorCode = "INVALID_INPUT" ErrorCodeMissingField ErrorCode = "MISSING_FIELD" ErrorCodeInvalidFormat ErrorCode = "INVALID_FORMAT" ErrorCodeValidationFailed ErrorCode = "VALIDATION_FAILED" // Database error codes ErrorCodeDatabaseError ErrorCode = "DATABASE_ERROR" ErrorCodeRecordNotFound ErrorCode = "RECORD_NOT_FOUND" ErrorCodeDuplicateRecord ErrorCode = "DUPLICATE_RECORD" ErrorCodeTransactionFailed ErrorCode = "TRANSACTION_FAILED" // Business logic error codes ErrorCodeInsufficientInventory ErrorCode = "INSUFFICIENT_INVENTORY" ErrorCodeInvalidOrderStatus ErrorCode = "INVALID_ORDER_STATUS" ErrorCodeInvalidPrice ErrorCode = "INVALID_PRICE" ErrorCodeInvalidQuantity ErrorCode = "INVALID_QUANTITY" ErrorCodeBusinessRuleViolation ErrorCode = "BUSINESS_RULE_VIOLATION" // External service error codes ErrorCodeExternalServiceError ErrorCode = "EXTERNAL_SERVICE_ERROR" ErrorCodeServiceTimeout ErrorCode = "SERVICE_TIMEOUT" // Idempotency and optimistic locking error codes ErrorCodeIdempotencyConflict ErrorCode = "IDEMPOTENCY_CONFLICT" ErrorCodeOptimisticLockConflict ErrorCode = "OPTIMISTIC_LOCK_CONFLICT" ErrorCodePreconditionFailed ErrorCode = "PRECONDITION_FAILED" ErrorCodeETagMismatch ErrorCode = "ETAG_MISMATCH" ErrorCodeVersionConflict ErrorCode = "VERSION_CONFLICT" // Internal error codes ErrorCodeInternalError ErrorCode = "INTERNAL_ERROR" ErrorCodeConfigError ErrorCode = "CONFIG_ERROR" )
func GetErrorCode ¶
GetErrorCode extracts error code from error
type ErrorHandler ¶
type ErrorHandler struct {
// contains filtered or unexported fields
}
ErrorHandler provides centralized error handling
func NewErrorHandler ¶
func NewErrorHandler(logger Logger) *ErrorHandler
NewErrorHandler creates a new error handler
func (*ErrorHandler) ErrorMiddleware ¶
func (h *ErrorHandler) ErrorMiddleware() gin.HandlerFunc
ErrorMiddleware returns a Gin middleware for error handling
func (*ErrorHandler) HandleError ¶
func (h *ErrorHandler) HandleError(c *gin.Context, err error)
HandleError processes errors and returns appropriate HTTP responses
func (*ErrorHandler) HandlePanic ¶
func (h *ErrorHandler) HandlePanic(c *gin.Context, recovered interface{})
HandlePanic handles panics and converts them to errors
func (*ErrorHandler) HandleValidationError ¶
func (h *ErrorHandler) HandleValidationError(c *gin.Context, validationErr *ValidationErrors)
HandleValidationError handles validation errors specifically
func (*ErrorHandler) RecoveryMiddleware ¶
func (h *ErrorHandler) RecoveryMiddleware() gin.HandlerFunc
RecoveryMiddleware returns a Gin middleware for panic recovery
type ErrorWithContext ¶
ErrorWithContext wraps an error with additional context
func NewErrorWithContext ¶
func NewErrorWithContext(err error, context map[string]interface{}) *ErrorWithContext
NewErrorWithContext creates a new error with context
func (*ErrorWithContext) Error ¶
func (e *ErrorWithContext) Error() string
func (*ErrorWithContext) Unwrap ¶
func (e *ErrorWithContext) Unwrap() error
type FilterParams ¶
type FilterParams struct {
Search string `json:"search"`
Category string `json:"category"`
OrgID string `json:"org_id"`
IsActive *bool `json:"is_active"`
DateFrom string `json:"date_from"`
DateTo string `json:"date_to"`
Extra map[string]string `json:"extra"`
}
FilterParams represents common filter parameters
func GetFilterParams ¶
func GetFilterParams(c *gin.Context) *FilterParams
GetFilterParams extracts filter parameters from the gin context
type IdempotencyManager ¶
type IdempotencyManager struct{}
IdempotencyManager manages idempotency operations
func NewIdempotencyManager ¶
func NewIdempotencyManager() *IdempotencyManager
NewIdempotencyManager creates a new idempotency manager
func (*IdempotencyManager) ExtractIdempotencyKey ¶
func (m *IdempotencyManager) ExtractIdempotencyKey(c *gin.Context) (string, bool)
ExtractIdempotencyKey extracts idempotency key from gin context
func (*IdempotencyManager) IsIdempotentRequest ¶
func (m *IdempotencyManager) IsIdempotentRequest(c *gin.Context) bool
IsIdempotentRequest checks if the request has an idempotency key
type Logger ¶
type Logger interface {
Error(msg string, fields ...interface{})
Warn(msg string, fields ...interface{})
Info(msg string, fields ...interface{})
}
Logger interface for error logging
type OptimisticLockError ¶
type OptimisticLockError struct {
EntityID string `json:"entity_id"`
ExpectedETag string `json:"expected_etag"`
CurrentETag string `json:"current_etag"`
CurrentVersion int64 `json:"current_version"`
LastModified time.Time `json:"last_modified"`
}
OptimisticLockError represents an optimistic locking conflict
func NewOptimisticLockError ¶
func NewOptimisticLockError(entityID, expectedETag, currentETag string, currentVersion int64, lastModified time.Time) *OptimisticLockError
NewOptimisticLockError creates a new optimistic locking error
func (*OptimisticLockError) Error ¶
func (e *OptimisticLockError) Error() string
func (*OptimisticLockError) ToAppError ¶
func (e *OptimisticLockError) ToAppError() *AppError
ToAppError converts OptimisticLockError to AppError
type OptimisticLockManager ¶
type OptimisticLockManager struct{}
OptimisticLockManager manages optimistic locking operations
func NewOptimisticLockManager ¶
func NewOptimisticLockManager() *OptimisticLockManager
NewOptimisticLockManager creates a new optimistic lock manager
func (*OptimisticLockManager) ExtractETagFromContext ¶
func (m *OptimisticLockManager) ExtractETagFromContext(c *gin.Context) (string, bool)
ExtractETagFromContext extracts ETag from gin context
func (*OptimisticLockManager) ExtractVersionFromContext ¶
func (m *OptimisticLockManager) ExtractVersionFromContext(c *gin.Context) (int64, bool)
ExtractVersionFromContext extracts version information from gin context
func (*OptimisticLockManager) PrepareForUpdate ¶
func (m *OptimisticLockManager) PrepareForUpdate(entity VersionedEntity)
PrepareForUpdate prepares an entity for update by incrementing version
func (*OptimisticLockManager) ValidateETag ¶
func (m *OptimisticLockManager) ValidateETag(entity VersionedEntity, expectedETag, currentETag string) error
ValidateETag validates that the entity ETag matches the expected ETag
func (*OptimisticLockManager) ValidateVersion ¶
func (m *OptimisticLockManager) ValidateVersion(entity VersionedEntity, expectedVersion int64) error
ValidateVersion validates that the entity version matches the expected version
type PaginationMeta ¶
type PaginationMeta struct {
Page int `json:"page" example:"1"` // Current page number
Limit int `json:"limit" example:"20"` // Items per page
Total int `json:"total" example:"100"` // Total number of items
TotalPages int `json:"total_pages" example:"5"` // Total number of pages
HasNext bool `json:"has_next" example:"true"` // Whether there is a next page
HasPrev bool `json:"has_prev" example:"false"` // Whether there is a previous page
}
PaginationMeta contains pagination information @Description Pagination metadata for list endpoints
func NewPaginationMeta ¶
func NewPaginationMeta(page, limit, total int) *PaginationMeta
NewPaginationMeta creates pagination metadata
type PaginationParams ¶
PaginationParams represents pagination parameters from the request
func GetPaginationParams ¶
func GetPaginationParams(c *gin.Context) *PaginationParams
GetPaginationParams extracts pagination parameters from the gin context
func (*PaginationParams) CalculateOffset ¶
func (p *PaginationParams) CalculateOffset() int
CalculateOffset calculates the database offset for pagination
func (*PaginationParams) Validate ¶
func (p *PaginationParams) Validate() error
Validate validates pagination parameters
type PaginationRequest ¶
PaginationRequest represents pagination parameters for repository operations
type Response ¶
type Response struct {
Data interface{} `json:"data,omitempty"` // Response data payload
Meta *ResponseMeta `json:"meta,omitempty" swaggertype:"object"` // Response metadata including trace ID and pagination
Error *ResponseError `json:"error,omitempty" swaggertype:"object"` // Error details if request failed
}
Response represents a standardized API response @Description Standard API response structure used across all endpoints
func BuildPaginationResponse ¶
func BuildPaginationResponse(data interface{}, total int, params *PaginationParams) *Response
BuildPaginationResponse builds a complete pagination response
type ResponseError ¶
type ResponseError struct {
Code string `json:"code" example:"INVALID_INPUT"` // Error code for programmatic handling
Message string `json:"message" example:"Invalid input data"` // Human-readable error message
Details map[string]interface{} `json:"details,omitempty" swaggertype:"object"` // Additional error details
}
ResponseError represents an error response @Description Error details when a request fails
type ResponseMeta ¶
type ResponseMeta struct {
TraceID string `json:"trace_id,omitempty" example:"abc123xyz"` // Request trace ID for debugging
Pagination *PaginationMeta `json:"pagination,omitempty" swaggertype:"object"` // Pagination information for list endpoints
Timestamp string `json:"timestamp,omitempty" example:"2025-01-05T10:30:00Z"` // Response timestamp
Extra map[string]interface{} `json:"extra,omitempty" swaggertype:"object"` // Additional metadata
}
ResponseMeta contains metadata about the response @Description Metadata included in API responses for tracing and pagination
type RetryConfig ¶
type RetryConfig struct {
MaxAttempts int `json:"max_attempts"`
InitialDelay time.Duration `json:"initial_delay"`
MaxDelay time.Duration `json:"max_delay"`
BackoffFactor float64 `json:"backoff_factor"`
Jitter bool `json:"jitter"`
RetryableErrors []error `json:"-"`
}
RetryConfig defines retry behavior
func DefaultRetryConfig ¶
func DefaultRetryConfig() *RetryConfig
DefaultRetryConfig returns a default retry configuration
type RetryableOperation ¶
RetryableOperation represents an operation that can be retried
type SortParams ¶
type SortParams struct {
SortBy string `json:"sort_by"`
SortOrder string `json:"sort_order"` // "asc" or "desc"
}
SortParams represents sorting parameters from the request
func GetSortParams ¶
func GetSortParams(c *gin.Context) *SortParams
GetSortParams extracts sorting parameters from the gin context
type ValidationErrors ¶
ValidationErrors represents multiple validation errors
func NewValidationErrors ¶
func NewValidationErrors() *ValidationErrors
NewValidationErrors creates a new ValidationErrors
func (*ValidationErrors) Add ¶
func (v *ValidationErrors) Add(field, message string)
func (*ValidationErrors) Error ¶
func (v *ValidationErrors) Error() string
func (*ValidationErrors) HasErrors ¶
func (v *ValidationErrors) HasErrors() bool
func (*ValidationErrors) ToAppError ¶
func (v *ValidationErrors) ToAppError() *AppError
ToAppError converts ValidationErrors to AppError