package response import ( "encoding/json" "log/slog" "net/http" ) // ErrorBody is the standard JSON error response shape. type ErrorBody struct { Error string `json:"error"` Message string `json:"message,omitempty"` } // JSON writes a JSON body with status code and Content-Type. func JSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) if v != nil { _ = json.NewEncoder(w).Encode(v) } } // OK writes 200 with optional JSON body. func OK(w http.ResponseWriter, v any) { if v == nil { w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) return } JSON(w, http.StatusOK, v) } // Error writes a JSON error response. func Error(w http.ResponseWriter, status int, err string, message string) { JSON(w, status, ErrorBody{Error: err, Message: message}) } // BadRequest writes 400 with error message. func BadRequest(w http.ResponseWriter, message string) { Error(w, http.StatusBadRequest, "bad_request", message) } // InternalError writes 500 and logs the err. func InternalError(w http.ResponseWriter, message string, logErr error) { if logErr != nil { slog.Error(message, "err", logErr) } Error(w, http.StatusInternalServerError, "internal_error", message) } // NotFound writes 404. func NotFound(w http.ResponseWriter, message string) { Error(w, http.StatusNotFound, "not_found", message) }