Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why prepare_payload removes Transfer-Encoding: chunked from http::response?

I create http::response<string_body> and call prepare_payload() after the response is built like this

http::response<http::string_body> res;

res.version(11);
res.result(http::status::ok);
res.set(http::field::server, "Example-Server");
res.body() = "test";

// Chunked transfer encoding
res.chunked(true);

std::cout << res;
res.prepare_payload();
std::cout << res;

After calling res.prepare_payload() for some reason the Transfer-Encoding: chunked header is removed and replaced with Content-Length: 4 header:

Before prepare_payload():

HTTP/1.1 200 OK

Server: Example-Server

Transfer-Encoding: chunked

4 test

0

After prepare_payload()

HTTP/1.1 200 OK

Server: Example-Server

Content-Length: 4

test

Why is the Transfer-Encoding header replaced with Content-Length after calling res.prepare_payload() and should res.prepare_payload() be called in case of chunked responses?

like image 347
Joe J Avatar asked Dec 22 '25 13:12

Joe J


1 Answers

Beast is opinionated and avoids chunked encoding if the content length is known ahead of time.

Prepare-payload asks Beast to do what it thinks best, depending on the type of body, http version, status-code and content length if known.

You can easily force chunked encoding if you insist, by simply re-ordering your instructions:

#include <boost/beast.hpp>
#include <iostream>
namespace http = boost::beast::http;

int main() {
    http::response<http::string_body> res;

    res.version(11);
    res.result(http::status::ok);
    res.set(http::field::server, "Example-Server");
    res.body() = "test";

    res.prepare_payload();

    // Chunked transfer encoding
    res.chunked(true);
    std::cout << res;
}

Printing Live On Coliru

Server: Example-Server
Transfer-Encoding: chunked

4
test
0
like image 171
sehe Avatar answered Dec 24 '25 01:12

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!