common

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2025 License: GPL-3.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
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")
	ErrUnauthorized               = errors.New("unauthorized")

	// 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
	ErrExternalServiceUnavailable = errors.New("external service unavailable")
	ErrExternalServiceTimeout     = errors.New("external service timeout")
	ErrExternalServiceError       = errors.New("external service error")
)

Common error definitions

Functions

func AsError

func AsError(err error, target interface{}) bool

AsError attempts to extract an error of a specific type

func BadRequest

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

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 Error

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

Error sends an error response

func Forbidden

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

Forbidden sends a 403 Forbidden response

func GetOrganizationID

func GetOrganizationID(c *gin.Context) (string, bool)

GetOrganizationID extracts the organization ID from the gin context It tries multiple key variants to ensure compatibility across all handlers

func GetStatusCode

func GetStatusCode(err error) int

GetStatusCode extracts HTTP status code from error

func GetSubjectID

func GetSubjectID(c *gin.Context) (string, bool)

GetSubjectID extracts the subject ID (user ID) from the gin context It tries multiple key variants to ensure compatibility

func GetTraceID

func GetTraceID(c *gin.Context) string

GetTraceID extracts the trace ID from the gin context

func GetUserRoles

func GetUserRoles(c *gin.Context) ([]string, bool)

GetUserRoles retrieves the user roles from the gin context

func InternalServerError

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

InternalServerError sends a 500 Internal Server Error response

func IsAdmin

func IsAdmin(c *gin.Context) bool

IsAdmin checks if the user has admin, super_admin, or ecom_admin role

func IsError

func IsError(err error, target error) bool

IsError checks if an error is of a specific type

func NotFound

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

NotFound sends a 404 Not Found 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

func Unauthorized

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

Unauthorized sends a 401 Unauthorized 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

func IsAppError(err error) (*AppError, bool)

IsAppError checks if an error is an AppError

func NewAppError

func NewAppError(code ErrorCode, message string, statusCode int) *AppError

NewAppError creates a new AppError

func NewBusinessRuleError

func NewBusinessRuleError(rule string, details string) *AppError

NewBusinessRuleError creates a business rule violation error

func NewDatabaseError

func NewDatabaseError(operation string, cause error) *AppError

NewDatabaseError creates a database error

func NewETagMismatchError

func NewETagMismatchError(expected, actual string) *AppError

NewETagMismatchError creates an ETag mismatch error

func NewExternalServiceError

func NewExternalServiceError(service string, cause error) *AppError

NewExternalServiceError creates an external service error

func NewForbiddenError

func NewForbiddenError(message string) *AppError

NewForbiddenError creates a forbidden error

func NewIdempotencyConflictError

func NewIdempotencyConflictError(message string) *AppError

NewIdempotencyConflictError creates an idempotency conflict error

func NewInternalError

func NewInternalError(message string) *AppError

NewInternalError creates an internal server error

func NewNotFoundError

func NewNotFoundError(resource string) *AppError

NewNotFoundError creates a not found error

func NewOptimisticLockConflictError

func NewOptimisticLockConflictError(message string) *AppError

NewOptimisticLockConflictError creates an optimistic locking conflict error

func NewPreconditionFailedError

func NewPreconditionFailedError(message string) *AppError

NewPreconditionFailedError creates a precondition failed error

func NewUnauthorizedError

func NewUnauthorizedError(message string) *AppError

NewUnauthorizedError creates an unauthorized error

func NewValidationError

func NewValidationError(message string) *AppError

NewValidationError creates a validation error

func NewVersionConflictError

func NewVersionConflictError(expected, actual int64) *AppError

NewVersionConflictError creates a version conflict error

func WrapError

func WrapError(err error, code ErrorCode, message string, statusCode int) *AppError

WrapError wraps a generic error as an AppError

func (*AppError) Error

func (e *AppError) Error() string

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

func (*AppError) WithCause

func (e *AppError) WithCause(cause error) *AppError

WithCause adds a cause error to an AppError

func (*AppError) WithContext

func (e *AppError) WithContext(key string, value interface{}) *AppError

WithContext adds context to an AppError

func (*AppError) WithField

func (e *AppError) WithField(field, message string) *AppError

WithField adds a field error 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"
	ErrorCodeUnauthorized ErrorCode = "UNAUTHORIZED"

	// 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"
	ErrorCodeServiceUnavailable   ErrorCode = "SERVICE_UNAVAILABLE"
	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

func GetErrorCode(err error) ErrorCode

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

type ErrorWithContext struct {
	Err     error
	Context map[string]interface{}
}

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

type PaginationParams struct {
	Page  int `json:"page"`
	Limit int `json:"limit"`
}

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

type PaginationRequest struct {
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

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

type RetryableOperation func(ctx context.Context, attempt int) error

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

type ValidationErrors struct {
	Errors map[string]string `json:"errors"`
}

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

type VersionedEntity

type VersionedEntity interface {
	GetID() string
	GetVersion() int64
	GetUpdatedAt() time.Time
	IncrementVersion()
}

VersionedEntity represents an entity with version information for optimistic locking

Jump to

Keyboard shortcuts

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