Documentation
¶
Overview ¶
Package api provides shared REST API response envelope and error types.
Index ¶
- Constants
- func RequestID(r *http.Request) string
- func RespondError(w http.ResponseWriter, r *http.Request, err *APIError)
- func RespondJSON(w http.ResponseWriter, r *http.Request, statusCode int, data interface{}, ...)
- func RespondNoContent(w http.ResponseWriter)
- type APIError
- type ErrorDetail
- type ErrorEnvelope
- type ErrorPayload
- type Meta
- type SuccessEnvelope
Constants ¶
const ( CodeForbidden = "FORBIDDEN" CodeValidationError = "VALIDATION_ERROR" CodeNotFound = "NOT_FOUND" CodeConflict = "CONFLICT" CodeRateLimitExceeded = "RATE_LIMIT_EXCEEDED" CodeInternalError = "INTERNAL_ERROR" CodeBadRequest = "BAD_REQUEST" CodeUnprocessableEntity = "UNPROCESSABLE_ENTITY" )
Error codes for the API error envelope.
Variables ¶
This section is empty.
Functions ¶
func RequestID ¶
RequestID returns the request ID from the request (X-Request-ID header) or a new UUID.
func RespondError ¶
func RespondError(w http.ResponseWriter, r *http.Request, err *APIError)
RespondError writes the error envelope and sets status code. Uses X-Request-ID from r or generates one.
func RespondJSON ¶
func RespondJSON(w http.ResponseWriter, r *http.Request, statusCode int, data interface{}, meta *Meta)
RespondJSON writes a success response with envelope: { "data": data, "meta": meta }.
func RespondNoContent ¶
func RespondNoContent(w http.ResponseWriter)
RespondNoContent writes 204 with no body.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int `json:"-"`
Code string `json:"code"`
Message string `json:"message"`
Details []ErrorDetail `json:"details,omitempty"`
}
APIError carries status code and error code for handlers.
type ErrorDetail ¶
ErrorDetail is a field-level validation error.
type ErrorEnvelope ¶
type ErrorEnvelope struct {
Error ErrorPayload `json:"error"`
}
ErrorEnvelope is the standard error response shape: { "error": { "code", "message", "requestId", "details" } }.
type ErrorPayload ¶
type ErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"requestId,omitempty"`
Details []ErrorDetail `json:"details,omitempty"`
}
ErrorPayload is the inner error object.
type Meta ¶
type Meta struct {
RequestID string `json:"requestId,omitempty"`
}
Meta holds optional response metadata (e.g. requestId, pagination).
type SuccessEnvelope ¶
type SuccessEnvelope struct {
Data interface{} `json:"data"`
Meta *Meta `json:"meta,omitempty"`
}
SuccessEnvelope is the standard success response shape: { "data": ..., "meta": ... }.