| 436 | } |
| 437 | |
| 438 | void server_http_context::post(const std::string & path, const server_http_context::handler_t & handler) const { |
| 439 | pimpl->srv->Post(path_prefix + path, [handler](const httplib::Request & req, httplib::Response & res) { |
| 440 | std::string body = req.body; |
| 441 | std::map<std::string, raw_buffer> files; |
| 442 | |
| 443 | if (req.is_multipart_form_data()) { |
| 444 | // translate text fields to a JSON object and use it as the body |
| 445 | json form_json = json::object(); |
| 446 | for (const auto & [key, field] : req.form.fields) { |
| 447 | if (form_json.contains(key)) { |
| 448 | // if the key already exists, convert it to an array |
| 449 | if (!form_json[key].is_array()) { |
| 450 | json existing_value = form_json[key]; |
| 451 | form_json[key] = json::array({existing_value}); |
| 452 | } |
| 453 | form_json[key].push_back(field.content); |
| 454 | } else { |
| 455 | form_json[key] = field.content; |
| 456 | } |
| 457 | } |
| 458 | body = form_json.dump(); |
| 459 | |
| 460 | // populate files from multipart form |
| 461 | for (const auto & [key, file] : req.form.files) { |
| 462 | files[key] = raw_buffer(file.content.begin(), file.content.end()); |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | server_http_req_ptr request = std::make_unique<server_http_req>(server_http_req{ |
| 467 | get_params(req), |
| 468 | get_headers(req), |
| 469 | req.path, |
| 470 | build_query_string(req), |
| 471 | body, |
| 472 | std::move(files), |
| 473 | req.is_connection_closed |
| 474 | }); |
| 475 | server_http_res_ptr response = handler(*request); |
| 476 | process_handler_response(std::move(request), response, res); |
| 477 | }); |
| 478 | } |
| 479 | |