feat(api): standardize response envelope behavior

Add shared response DTOs and enhance the response envelope middleware with
excluded paths, trace ID generation fallback, and automatic extraction of
error details from handler responses. Update default business code mapping
for 503 and 504, and adjust idempotency detection to only treat the new
envelope format as already-wrapped.

BREAKING CHANGE: responses using the old envelope format (e.g., string
`code`) are now wrapped into the new standard envelope.
This commit is contained in:
zenfun
2026-01-10 00:59:45 +08:00
parent 6af938448e
commit 26733be020
3 changed files with 238 additions and 32 deletions

60
internal/dto/response.go Normal file
View File

@@ -0,0 +1,60 @@
package dto
// ResponseEnvelope is the standard API response wrapper.
// All JSON API responses are wrapped in this envelope format.
// @Description Standard API response envelope
type ResponseEnvelope struct {
// Business code: 0 for success, non-zero for errors
// 0 = success
// 1xxx = common errors (invalid param, unauthorized, forbidden, rate limited)
// 4xxx = client errors (resource not found, conflict, invalid state)
// 5xxx = server errors (internal error, service unavailable, timeout)
Code int `json:"code" example:"0"`
// Human-readable message: "success" for success, error description for errors
Message string `json:"message" example:"success"`
// Response data: business payload for success, null for errors
Data any `json:"data"`
// Request trace ID for debugging and log correlation
TraceID string `json:"trace_id" example:"a1b2c3d4e5f6g7h8"`
// Optional error details (e.g., field validation errors)
Details any `json:"details,omitempty"`
}
// ErrorResponse is returned when an error occurs.
// @Description Error response format
type ErrorResponse struct {
// Business error code (non-zero)
Code int `json:"code" example:"4001"`
// Error message
Message string `json:"message" example:"resource not found"`
// Always null for errors
Data any `json:"data" example:"null"`
// Request trace ID
TraceID string `json:"trace_id" example:"a1b2c3d4e5f6g7h8"`
// Optional structured error details
Details any `json:"details,omitempty"`
}
// SuccessResponse is returned for successful operations.
// @Description Success response format
type SuccessResponse struct {
// Always 0 for success
Code int `json:"code" example:"0"`
// Always "success"
Message string `json:"message" example:"success"`
// Response payload
Data any `json:"data"`
// Request trace ID
TraceID string `json:"trace_id" example:"a1b2c3d4e5f6g7h8"`
}