response

package
v0.5.5 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 6 Imported by: 3 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package response provides standardized JSON response types and helpers using a 7-digit composite code (HTTP_STATUS + SERVICE_CODE + CASE_CODE).

Role in architecture:

  • Shared adapter output: used by handlers to write consistent JSON and by handler package for error mapping.

Responsibilities:

  • Build and parse composite response codes (codes.go).
  • Write success, error, validation, pagination, and custom responses to Gin context (response.go, validation.go, pagination.go).
  • Format go-playground/validator errors into Laravel-style field maps (validation.go).

Constraints:

  • No business logic; only response shape and code building.
  • Service and case codes are defined in this package; callers pass them from response package constants.

This package must NOT:

  • Perform I/O except writing to gin.Context.
  • Depend on domain or use-case packages.

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
	ServiceCodeWallet                      = "16" // Wallet service
	ServiceCodePhone                       = "17" // Phone / phone verification service
	ServiceCodeEmail                       = "18" // Email / email verification service
	ServiceCodeTwoFactor                   = "19" // Two-factor authentication service
	ServiceCodeBank                        = "20" // Bank service
	ServiceCodeBankAccount                 = "21" // Bank account 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

	// Email change (70-74)
	CaseCodeEmailChangeRequested    = "70" // Email change OTP sent
	CaseCodeEmailChangeVerified     = "71" // Email change confirmed
	CaseCodeEmailChangeCancelled    = "72" // Email change cancelled
	CaseCodeEmailAlreadyUsed        = "73" // Email already registered to another account
	CaseCodeEmailVerificationFailed = "74" // Email OTP verification failed

	// Phone change (75-79)
	CaseCodePhoneChangeRequested    = "75" // Phone change OTP sent
	CaseCodePhoneChangeVerified     = "76" // Phone change confirmed
	CaseCodePhoneChangeCancelled    = "77" // Phone change cancelled
	CaseCodePhoneAlreadyUsed        = "78" // Phone already registered to another account
	CaseCodePhoneVerificationFailed = "79" // Phone OTP verification failed

	// Two-factor authentication (80-89)
	CaseCode2FAEnabled             = "80" // 2FA enabled
	CaseCode2FADisabled            = "81" // 2FA disabled
	CaseCode2FASetupInitiated      = "82" // 2FA setup started (secret + QR generated)
	CaseCode2FASetupVerified       = "83" // 2FA setup confirmed with valid OTP
	CaseCode2FAInvalidCode         = "84" // 2FA code invalid or expired
	CaseCode2FACodeRequired        = "85" // 2FA code missing from request
	CaseCode2FANotEnabled          = "86" // 2FA not enabled on account
	CaseCode2FAAlreadyEnabled      = "87" // 2FA already enabled
	CaseCode2FARecoveryCodeUsed    = "88" // 2FA bypass via recovery code
	CaseCode2FARecoveryCodeInvalid = "89" // Recovery code invalid or already used

	// Bank (90-94)
	CaseCodeBankNotFound      = "90" // Bank not found
	CaseCodeBankInactive      = "91" // Bank is inactive / not available
	CaseCodeBankAlreadyExists = "92" // Bank already registered
	CaseCodeBankCreated       = "93" // Bank created
	CaseCodeBankUpdated       = "94" // Bank updated

	// Bank account (95-99)
	CaseCodeBankAccountNotFound      = "95" // Bank account not found
	CaseCodeBankAccountInvalid       = "96" // Bank account number invalid or unverifiable
	CaseCodeBankAccountAlreadyExists = "97" // Bank account already registered
	CaseCodeBankAccountCreated       = "98" // Bank account created
	CaseCodeBankAccountDeleted       = "99" // Bank account deleted
)

Case codes (2 digits: 01-99)

View Source
const (
	DefaultPageNumber = 1
	DefaultPageSize   = 10
	MaxPageSize       = 100
)

DefaultPageNumber, DefaultPageSize, and MaxPageSize are the pagination defaults and cap used by handler and repository.

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 writes a cursor-based paginated JSON response using the given pagination payload.

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 converts err into a map of field names to error message slices. If err is validator.ValidationErrors, fields are mapped; otherwise returns {"general": [err.Error()]}.

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 splits a 7-digit code into httpStatus (first 3 digits), serviceCode (next 2), caseCode (last 2). Codes shorter than 7 digits return zero values.

func Result

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

Result writes a JSON response with the given HTTP status and composite code (BuildResponseCode(httpStatus, serviceCode, caseCode)).

func ResultWithCode

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

ResultWithCode writes a JSON response with explicit responseCode (no BuildResponseCode).

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"`
}

CommonResponse is the standard JSON body: code (7-digit composite), message, 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 is the top-level JSON shape for cursor-based pagination (code, message, data, nextCursor, hasNext).

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 holds data, nextCursor, and hasNext for cursor-based pagination (used with CursorPaginated).

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 is the top-level JSON shape for offset pagination (code, message, data, pageNumber, pageSize, hasNext, hasPrev).

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 holds data and pagination state for offset-based pagination (used with SimplePaginated).

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 is the JSON shape for 422 validation errors (code, message, errors map).

Jump to

Keyboard shortcuts

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