How can we respond to HTTP request with raw binary data from memory using Boost and Beast?
I'm adding an HTTP server to a c++ application to help other clients communicate with it. I created a few API's that respond with JSON but I want to add an API that responds with raw binary data from dynamically computed images. This could work if I save the image to the file system and then read it from there but I want better performance. I want to skip writing and reading the file system since I already have the content in RAM. I can send content from a string like this where resultContent is dynamically generated JSON-formatted string: std::string resultContent = handleAPIGetRequest(req.target()); http::file_body::value_type body; auto const size = resultContent.size(); http::response<http::string_body> res{ http::status::ok, req.version() }; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, mime_type(".json")); res.content_length(size); res.body() = resultContent; res.keep_alive(req.keep_alive()); return send(std::move(res)); Here is how a file is sent. This can send the raw image data from a PNG file but it requires having a file in the file system: beast::error_code ec; http::file_body::value_type body; body.open(path.c_str(), beast::file_mode::scan, ec); http::response<http::file_body> res{ std::piecewise_construct, std::make_tuple(std::move(body)), std::make_tuple(http::status::ok, req.version())}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, mime_type(path)); res.content_length(size); res.keep_alive(req.keep_alive()); return send(std::move(res));