package handlers import ( "encoding/json" "errors" "net/http" "github.com/jackc/pgx/v5" ) // RespondJSON writes a JSON response with the given status code. func RespondJSON(w http.ResponseWriter, status int, data any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(data) } // RespondSuccess returns the common success envelope. func RespondSuccess(w http.ResponseWriter, data any) { RespondJSON(w, http.StatusOK, modelsAPIResponse{Code: 0, Message: "ok", Data: data}) } // RespondError returns the common error envelope. func RespondError(w http.ResponseWriter, status int, code int, message string) { RespondJSON(w, status, modelsAPIResponse{Code: code, Message: message, Data: nil}) } // MapError maps repository/ service errors to HTTP status and code. func MapError(err error) (status int, code int, message string) { if errors.Is(err, pgx.ErrNoRows) { return http.StatusNotFound, 10001, "resource not found" } return http.StatusInternalServerError, 10000, "internal server error" } type modelsAPIResponse struct { Code int `json:"code"` Message string `json:"message"` Data any `json:"data"` }