Search code examples
c++httpboostboost-beast

How do I convert a boost::beast's response<buffer_body> to a response<string_body>?


I need to convert boost::beast::http::response<boost::beast::http::buffer_body> to boost::beast::http::response<boost::beast::http::string_body>.

What's an elegant and efficient way of doing so using beast's api?

P.S.

I think serializing and parsing is not so efficient, and maybe there's a better way. But if that's the solution, since I'm new to beast I would be also glad to see an elegant code example for that.

Thanks, David.


Solution

  • OK, I managed to do it

    boost::beast::http::response<boost::beast::http::string_body> string_response;
    boost::beast::http::response<boost::beast::http::buffer_body> buffer_response;
    std::string response_body
    
    // Do stuff to read the response and fill the response_body using the buffer
    
    string_response.base() = buffer_response.base();
    string_response.body() = response_body;
    

    It turns out that the header has a copy constructor, so all I had to do is assign the string body..

    So if the copy constructor is efficient (odds are that it is), this solution is also efficient.