Skip to content

Commit d32f04a

Browse files
Refactor EventsHandler to stream responses via chunked encoding
1 parent 3832bb4 commit d32f04a

File tree

1 file changed

+12
-18
lines changed

1 file changed

+12
-18
lines changed

lib/remote/eventshandler.cpp

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -102,33 +102,27 @@ bool EventsHandler::HandleRequest(
102102

103103
EventsSubscriber subscriber (std::move(eventTypes), HttpUtility::GetLastParameter(params, "filter"), l_ApiQuery);
104104

105-
server.StartDetectClientSideShutdown();
105+
IoBoundWorkSlot dontLockTheIoThread (yc);
106106

107107
response.result(http::status::ok);
108108
response.set(http::field::content_type, "application/json");
109+
response.StartStreaming(true);
110+
// Send response headers before waiting for the first event.
111+
response.Flush(yc);
109112

110-
IoBoundWorkSlot dontLockTheIoThread (yc);
111-
112-
http::async_write(stream, response, yc);
113-
stream.async_flush(yc);
114-
115-
asio::const_buffer newLine ("\n", 1);
113+
auto encoder = response.GetJsonEncoder();
116114

117115
for (;;) {
118116
auto event (subscriber.GetInbox()->Shift(yc));
119117

120-
if (event) {
121-
String body = JsonEncode(event);
122-
123-
boost::algorithm::replace_all(body, "\n", "");
124-
125-
asio::const_buffer payload (body.CStr(), body.GetLength());
126-
127-
asio::async_write(stream, payload, yc);
128-
asio::async_write(stream, newLine, yc);
129-
stream.async_flush(yc);
130-
} else if (server.Disconnected()) {
118+
if (response.IsClientDisconnected()) {
131119
return true;
132120
}
121+
122+
if (event) {
123+
encoder.Encode(event);
124+
response.body() << '\n';
125+
response.Flush(yc);
126+
}
133127
}
134128
}

0 commit comments

Comments
 (0)