json_http.cpp 615 B

123456789101112131415161718192021
  1. #include "json_http.hpp"
  2. #include "errors.hpp"
  3. namespace svapi {
  4. nlohmann::json bodyJson(const httplib::Request& req) {
  5. if (req.body.empty()) return nlohmann::json::object();
  6. try {
  7. return nlohmann::json::parse(req.body);
  8. } catch (const std::exception& e) {
  9. throw ApiError(ErrCode::BadRequest, "invalid_json",
  10. std::string("request body is not valid JSON: ") + e.what());
  11. }
  12. }
  13. void sendJson(httplib::Response& res, int status, const nlohmann::json& body) {
  14. res.status = status;
  15. res.set_content(body.dump(), "application/json");
  16. }
  17. } // namespace svapi