Skip to content

Instantly share code, notes, and snippets.

@cbodley
Created March 30, 2017 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbodley/a25282de38286f4cba8f172f9f5f9dc6 to your computer and use it in GitHub Desktop.
Save cbodley/a25282de38286f4cba8f172f9f5f9dc6 to your computer and use it in GitHub Desktop.
/// streaming message body interface
struct streaming_body {
using value_type = boost::asio::mutable_buffer;
class reader {
value_type& buffer;
public:
using mutable_buffers_type = boost::asio::mutable_buffers_1;
template<bool isRequest, class Fields>
explicit reader(beast::http::message<isRequest, streaming_body, Fields>& m)
: buffer(m.body)
{}
void init(const boost::optional<uint64_t>& content_length) {}
void finish() {}
mutable_buffers_type prepare(size_t n) {
n = std::min(n, boost::asio::buffer_size(buffer));
auto position = boost::asio::buffer_cast<char*>(buffer);
return {position, n};
}
void commit(size_t n) {
buffer = buffer + n;
}
};
};
using header_type = beast::http::fields;
using parser_type = beast::http::message_parser<true, streaming_body, header_type>;
using tcp = boost::asio::ip::tcp;
// read up to 'max' bytes of body data into the given 'buf'
int read_some_body(tcp::socket& socket, parser_type& parser,
flat_streambuf& parse_buffer, char* buf, size_t max)
{
// assign the given buffer as the message body. beast::http::parse_some()
// will copy bytes from the parse_buffer and/or read bytes from the socket
// until this buffer is full
auto& message = parser.get();
auto& body_remaining = message.body;
body_remaining = boost::asio::mutable_buffer{buf, max};
while (boost::asio::buffer_size(body_remaining) &&
parser.need_more() && !parser.is_complete()) {
boost::system::error_code ec;
beast::http::parse_some(socket, parse_buffer, parser, ec);
if (ec == boost::asio::error::eof) {
break;
}
if (ec) {
throw boost::system::system_error(ec);
}
}
// return number of bytes read
return max - boost::asio::buffer_size(body_remaining);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment