Skip to content

Commit 986a20f

Browse files
authored
Resolve #2017 (#2022)
* Resolve #2017 * Fix warning * Update README
1 parent 8311e11 commit 986a20f

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,21 @@ int main(void)
125125
res.set_content(req.body, "text/plain");
126126
});
127127

128+
// If the handler takes time to finish, you can also poll the connection state
129+
svr.Get("/task", [&](const Request& req, Response& res) {
130+
const char * result = nullptr;
131+
process.run(); // for example, starting an external process
132+
while (result == nullptr) {
133+
sleep(1);
134+
if (req.is_connection_closed()) {
135+
process.kill(); // kill the process
136+
return;
137+
}
138+
result = process.stdout(); // != nullptr if the process finishes
139+
}
140+
res.set_content(result, "text/plain");
141+
});
142+
128143
svr.Get("/stop", [&](const Request& req, Response& res) {
129144
svr.stop();
130145
});

httplib.h

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,7 @@ struct Request {
628628
Ranges ranges;
629629
Match matches;
630630
std::unordered_map<std::string, std::string> path_params;
631+
std::function<bool()> is_connection_closed = []() { return true; };
631632

632633
// for client
633634
ResponseHandler response_handler;
@@ -2572,7 +2573,7 @@ inline bool is_field_content(const std::string &s) {
25722573

25732574
inline bool is_field_value(const std::string &s) { return is_field_content(s); }
25742575

2575-
}; // namespace fields
2576+
} // namespace fields
25762577

25772578
} // namespace detail
25782579

@@ -7217,6 +7218,11 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
72177218
}
72187219
}
72197220

7221+
// Setup `is_connection_closed` method
7222+
req.is_connection_closed = [&]() {
7223+
return !detail::is_socket_alive(strm.socket());
7224+
};
7225+
72207226
// Routing
72217227
auto routed = false;
72227228
#ifdef CPPHTTPLIB_NO_EXCEPTIONS

0 commit comments

Comments
 (0)