Files
language/backend/internal/handlers/response.go
T

45 lines
1.3 KiB
Go

package handlers
import (
"encoding/json"
"errors"
"net/http"
"github.com/fish/language/backend/internal/services"
"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"
}
if errors.Is(err, services.ErrCategoryNotEmpty) {
return http.StatusConflict, 10005, "category has words and cannot be deleted"
}
return http.StatusInternalServerError, 10000, "internal server error"
}
type modelsAPIResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data"`
}