@@ -146,6 +146,7 @@ struct Response {
146
146
int status;
147
147
Headers headers;
148
148
std::string body;
149
+ std::function<std::string (uint64_t offset)> streamcb;
149
150
150
151
bool has_header (const char * key) const ;
151
152
std::string get_header_value (const char * key) const ;
@@ -964,6 +965,17 @@ inline bool from_hex_to_i(const std::string& s, size_t i, size_t cnt, int& val)
964
965
return true ;
965
966
}
966
967
968
+ inline std::string from_i_to_hex (uint64_t n)
969
+ {
970
+ const char *charset = " 0123456789abcdef" ;
971
+ std::string ret;
972
+ do {
973
+ ret = charset[n & 15 ] + ret;
974
+ n >>= 4 ;
975
+ } while (n > 0 );
976
+ return ret;
977
+ }
978
+
967
979
inline size_t to_utf8 (int code, char * buff)
968
980
{
969
981
if (code < 0x0080 ) {
@@ -1586,13 +1598,34 @@ inline void Server::write_response(Stream& strm, bool last_connection, const Req
1586
1598
1587
1599
auto length = std::to_string (res.body .size ());
1588
1600
res.set_header (" Content-Length" , length.c_str ());
1601
+ } else if (res.streamcb ) {
1602
+ // Streamed response
1603
+ bool chunked_response = !res.has_header (" Content-Length" );
1604
+ if (chunked_response)
1605
+ res.set_header (" Transfer-Encoding" , " chunked" );
1589
1606
}
1590
1607
1591
1608
detail::write_headers (strm, res);
1592
1609
1593
1610
// Body
1594
- if (!res.body .empty () && req.method != " HEAD" ) {
1595
- strm.write (res.body .c_str (), res.body .size ());
1611
+ if (req.method != " HEAD" ) {
1612
+ if (!res.body .empty ()) {
1613
+ strm.write (res.body .c_str (), res.body .size ());
1614
+ } else if (res.streamcb ) {
1615
+ bool chunked_response = !res.has_header (" Content-Length" );
1616
+ uint64_t offset = 0 ;
1617
+ bool data_available = true ;
1618
+ while (data_available) {
1619
+ std::string chunk = res.streamcb (offset);
1620
+ offset += chunk.size ();
1621
+ data_available = !chunk.empty ();
1622
+ // Emit chunked response header and footer for each chunk
1623
+ if (chunked_response)
1624
+ chunk = detail::from_i_to_hex (chunk.size ()) + " \r\n " + chunk + " \r\n " ;
1625
+ if (strm.write (chunk.c_str (), chunk.size ()) < 0 )
1626
+ break ; // Stop on error
1627
+ }
1628
+ }
1596
1629
}
1597
1630
1598
1631
// Log
0 commit comments