response

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ServiceCodeCommon                      = "00" // Common/General services
	ServiceCodeAuth                        = "01" // Authentication service
	ServiceCodeTransaction                 = "02" // Transaction service
	ServiceCodeWithdrawal                  = "03" // Withdrawal service
	ServiceCodeUser                        = "04" // User service
	ServiceCodeAdmin                       = "05" // Admin service
	ServiceCodeMerchant                    = "06" // Merchant service
	ServiceCodeSetting                     = "07" // Setting service
	ServiceCodeRole                        = "08" // Role service
	ServiceCodePermission                  = "09" // Permission service
	ServiceCodeNotificationTemplate        = "10" // Notification template service
	ServiceCodeNotificationTemplateChannel = "11" // Notification template channel service
	ServiceCodeNotification                = "12" // Notification service
	ServiceCodeIPWhitelist                 = "13" // IP Whitelist service
	ServiceCodeApiKey                      = "14" // API Key service
	ServiceCodeDeposit                     = "15" // Deposit service
)

Service codes (2 digits: 00-06)

View Source
const (
	// Success cases (01-10)
	CaseCodeSuccess            = "01" // General success
	CaseCodeCreated            = "02" // Resource created
	CaseCodeUpdated            = "03" // Resource updated
	CaseCodeDeleted            = "04" // Resource deleted
	CaseCodeRetrieved          = "05" // Resource retrieved
	CaseCodeListRetrieved      = "06" // List retrieved
	CaseCodeLoginSuccess       = "07" // Login successful
	CaseCodeLogoutSuccess      = "08" // Logout successful
	CaseCodePasswordChanged    = "09" // Password changed
	CaseCodeOperationCompleted = "10" // Operation completed

	// Validation errors (11-20)
	CaseCodeValidationError  = "11" // General validation error
	CaseCodeRequiredField    = "12" // Required field missing
	CaseCodeInvalidFormat    = "13" // Invalid format
	CaseCodeInvalidValue     = "14" // Invalid value
	CaseCodeDuplicateEntry   = "15" // Duplicate entry
	CaseCodeInvalidEmail     = "16" // Invalid email format
	CaseCodeInvalidPassword  = "17" // Invalid password
	CaseCodePasswordTooShort = "18" // Password too short
	CaseCodeInvalidDate      = "19" // Invalid date format
	CaseCodeInvalidRange     = "20" // Invalid range

	// Authentication errors (21-30)
	CaseCodeUnauthorized       = "21" // Unauthorized access
	CaseCodeInvalidToken       = "22" // Invalid token
	CaseCodeTokenExpired       = "23" // Token expired
	CaseCodeInvalidCredentials = "24" // Invalid credentials
	CaseCodeAccountLocked      = "25" // Account locked
	CaseCodeAccountDisabled    = "26" // Account disabled
	CaseCodePermissionDenied   = "27" // Permission denied
	CaseCodeSessionExpired     = "28" // Session expired
	CaseCodeTwoFactorRequired  = "29" // Two-factor authentication required
	CaseCodeInvalidOTP         = "30" // Invalid OTP

	// Not found errors (31-40)
	CaseCodeNotFound                            = "31" // Resource not found
	CaseCodeUserNotFound                        = "32" // User not found
	CaseCodeAdminNotFound                       = "33" // Admin not found
	CaseCodeMerchantNotFound                    = "34" // Merchant not found
	CaseCodeTransactionNotFound                 = "35" // Transaction not found
	CaseCodeSettingNotFound                     = "36" // Setting not found
	CaseCodeRoleNotFound                        = "37" // Role not found
	CaseCodeNotificationTemplateNotFound        = "38" // Notification template not found
	CaseCodeNotificationTemplateChannelNotFound = "39" // Notification template channel not found
	CaseCodeNotificationNotFound                = "40" // Notification not found
	CaseCodeMethodNotFound                      = "41" // Method not found
	CaseCodeRouteNotFound                       = "42" // Route not found
	CaseCodeResourceNotFound                    = "43" // General resource not found
	CaseCodeApiKeyNotFound                      = "44" // API key not found

	// Business logic errors (45-53)
	CaseCodeInsufficientBalance = "45" // Insufficient balance
	CaseCodeInvalidAmount       = "46" // Invalid amount
	CaseCodeTransactionFailed   = "47" // Transaction failed
	CaseCodeLimitExceeded       = "48" // Limit exceeded
	CaseCodeInvalidStatus       = "49" // Invalid status
	CaseCodeOperationNotAllowed = "50" // Operation not allowed
	CaseCodeAlreadyProcessed    = "51" // Already processed
	CaseCodePendingTransaction  = "52" // Pending transaction
	CaseCodeExpiredTransaction  = "53" // Expired transaction
	CaseCodeInvalidCurrency     = "54" // Invalid currency

	// Server errors (55-63)
	CaseCodeInternalError        = "55" // Internal server error
	CaseCodeDatabaseError        = "56" // Database error
	CaseCodeExternalServiceError = "57" // External service error
	CaseCodeTimeout              = "58" // Request timeout
	CaseCodeServiceUnavailable   = "59" // Service unavailable
	CaseCodeMaintenance          = "60" // Under maintenance
	CaseCodeRateLimitExceeded    = "61" // Rate limit exceeded
	CaseCodeConfigurationError   = "62" // Configuration error
	CaseCodeEncryptionError      = "63" // Encryption error
	CaseCodeDecryptionError      = "64" // Decryption error

	// Conflict errors (65-69)
	CaseCodeConflict               = "65" // General conflict
	CaseCodeResourceExists         = "66" // Resource already exists
	CaseCodeConcurrentModification = "67" // Concurrent modification
	CaseCodeVersionMismatch        = "68" // Version mismatch
	CaseCodeStateConflict          = "69" // State conflict
)

Case codes (2 digits: 01-99)

Variables

This section is empty.

Functions

func BuildResponseCode

func BuildResponseCode(httpStatus int, serviceCode, caseCode string) int

BuildResponseCode builds a response code from HTTP status, service code, and case code Format: HTTP_STATUS_CODE (3 digits) + SERVICE_CODE (2 digits) + CASE_CODE (2 digits) Example: 2010301 = HTTP 201 + Service 03 (Withdrawal) + Case 01 (Success)

func ConflictError

func ConflictError(ctx *gin.Context, serviceCode string, message string)

ConflictError returns a 409 Conflict response

func Created

func Created(ctx *gin.Context, serviceCode string, data interface{}, message string)

Created returns a 201 Created response

func CursorPaginated

func CursorPaginated(ctx *gin.Context, httpStatus int, serviceCode, caseCode string, pagination CursorPaginationResponse, message string)

CursorPaginated returns a cursor-based paginated response with fields at the top level

func Deleted

func Deleted(ctx *gin.Context, serviceCode string, message string)

Deleted returns a 200 OK response for deletions

func Fail

func Fail(ctx *gin.Context)

Fail returns an internal server error response

func FailWithDetailed

func FailWithDetailed(ctx *gin.Context, httpStatus int, serviceCode, caseCode string, data interface{}, message string)

FailWithDetailed returns an error response with all parameters

func FailWithMessage

func FailWithMessage(ctx *gin.Context, message string)

FailWithMessage returns an internal server error with custom message

func ForbiddenError

func ForbiddenError(ctx *gin.Context, message string)

ForbiddenError returns a 403 Forbidden response

func FormatValidationError

func FormatValidationError(err error) map[string][]string

FormatValidationError formats validation errors in Laravel style

func GetJSONFieldName

func GetJSONFieldName(structType reflect.Type, fieldName string) string

GetJSONFieldName extracts JSON tag name from struct field

func NotFoundError

func NotFoundError(ctx *gin.Context, serviceCode, caseCode string, message string)

NotFoundError returns a 404 Not Found response

func Ok

func Ok(ctx *gin.Context)

Ok returns a successful response with default success code

func OkWithData

func OkWithData(ctx *gin.Context, data interface{})

OkWithData returns a successful response with data

func OkWithDetailed

func OkWithDetailed(ctx *gin.Context, httpStatus int, serviceCode, caseCode string, data interface{}, message string)

OkWithDetailed returns a response with all parameters

func OkWithMessage

func OkWithMessage(ctx *gin.Context, message string)

OkWithMessage returns a successful response with custom message

func ParseResponseCode

func ParseResponseCode(code int) (httpStatus int, serviceCode, caseCode string)

ParseResponseCode parses a response code into its components

func Result

func Result(ctx *gin.Context, httpStatus int, serviceCode, caseCode string, data interface{}, message string)

Result creates a response with custom code system

func ResultWithCode

func ResultWithCode(ctx *gin.Context, httpStatus int, responseCode int, data interface{}, message string)

ResultWithCode creates a response with explicit response code

func SimplePaginated

func SimplePaginated(ctx *gin.Context, httpStatus int, serviceCode, caseCode string, pagination SimplePaginationResponse, message string)

SimplePaginated returns a simple paginated response with fields at the top level

func UnauthorizedError

func UnauthorizedError(ctx *gin.Context, message string)

UnauthorizedError returns a 401 Unauthorized response

func Updated

func Updated(ctx *gin.Context, serviceCode string, data interface{}, message string)

Updated returns a 200 OK response for updates

func ValidationError

func ValidationError(ctx *gin.Context, serviceCode string, err error)

ValidationError returns a 400 Bad Request for validation errors in Laravel style

func ValidationErrorSimple

func ValidationErrorSimple(ctx *gin.Context, serviceCode string, fieldName string, errorMessage string)

ValidationErrorSimple returns a 422 Unprocessable Entity for simple validation errors (single field)

func ValidationErrorWithMessage

func ValidationErrorWithMessage(ctx *gin.Context, serviceCode string, message string, errors map[string][]string)

ValidationErrorWithMessage returns a 422 Unprocessable Entity for validation errors with custom message and errors map

Types

type CommonResponse

type CommonResponse struct {
	Code    int         `json:"code"` // Custom response code: HTTP_STATUS + SERVICE_CODE + CASE_CODE (e.g., 2000401)
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

type CursorPaginatedResponse

type CursorPaginatedResponse struct {
	Code       int         `json:"code"`       // Custom response code
	Message    string      `json:"message"`    // Response message
	Data       interface{} `json:"data"`       // The actual data array
	NextCursor *string     `json:"nextCursor"` // Cursor for the next page (null if no more pages)
	HasNext    bool        `json:"hasNext"`    // Whether there are more items available
}

CursorPaginatedResponse represents a cursor-based pagination response with fields at the top level

type CursorPaginationResponse

type CursorPaginationResponse struct {
	Data       interface{} `json:"data"`       // The actual data array
	NextCursor *string     `json:"nextCursor"` // Cursor for the next page (null if no more pages)
	HasNext    bool        `json:"hasNext"`    // Whether there are more items available
}

CursorPaginationResponse represents cursor-based pagination response

type SimplePaginatedResponse

type SimplePaginatedResponse struct {
	Code       int         `json:"code"`       // Custom response code
	Message    string      `json:"message"`    // Response message
	Data       interface{} `json:"data"`       // The actual data array
	PageNumber int         `json:"pageNumber"` // Current page number
	PageSize   int         `json:"pageSize"`   // Number of items per page
	HasNext    bool        `json:"hasNext"`    // Whether there is a next page
	HasPrev    bool        `json:"hasPrev"`    // Whether there is a previous page
}

SimplePaginatedResponse represents a simple pagination response with fields at the top level

type SimplePaginationResponse

type SimplePaginationResponse struct {
	Data       interface{} `json:"data"`       // The actual data array
	PageNumber int         `json:"pageNumber"` // Current page number
	PageSize   int         `json:"pageSize"`   // Number of items per page
	HasNext    bool        `json:"hasNext"`    // Whether there is a next page
	HasPrev    bool        `json:"hasPrev"`    // Whether there is a previous page
}

SimplePaginationResponse represents simple offset-based pagination response

type ValidationErrorResponse

type ValidationErrorResponse struct {
	Code    int                 `json:"code"`    // Custom response code
	Message string              `json:"message"` // General error message
	Errors  map[string][]string `json:"errors"`  // Field-specific errors
}

ValidationErrorResponse represents Laravel-style validation error response

Jump to

Keyboard shortcuts

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