Rework the body of request and response

This commit is contained in:
Chunting Gu
2019-07-03 17:37:44 +08:00
parent b9f2ba6a41
commit 98aeeae012
39 changed files with 1122 additions and 677 deletions
+55 -24
View File
@@ -91,7 +91,7 @@ void Connection::OnRead(boost::system::error_code ec, std::size_t length) {
return;
}
LOG_VERB("HTTP request:\n%s", request_->Dump(4, "> ").c_str());
LOG_VERB("HTTP request:\n%s", request_->Dump().c_str());
// Enqueue this connection.
// Some worker thread will handle it later.
@@ -99,36 +99,67 @@ void Connection::OnRead(boost::system::error_code ec, std::size_t length) {
}
void Connection::DoWrite() {
LOG_VERB("HTTP response:\n%s", response_->Dump(4, "> ").c_str());
LOG_VERB("HTTP response:\n%s", response_->Dump().c_str());
boost::asio::async_write(socket_, response_->payload(),
std::bind(&Connection::OnWrite, shared_from_this(),
std::placeholders::_1,
// Firstly, write the headers.
boost::asio::async_write(socket_, response_->GetPayload(),
std::bind(&Connection::OnWriteHeaders,
shared_from_this(), std::placeholders::_1,
std::placeholders::_2));
}
// NOTE:
// This write handler will be called from main thread (the thread calling
// io_context.run), even though AsyncWrite() is invoked by worker threads.
// This is ensured by Asio.
void Connection::OnWrite(boost::system::error_code ec, std::size_t length) {
void Connection::OnWriteHeaders(boost::system::error_code ec,
std::size_t length) {
if (ec) {
LOG_ERRO("Socket write error (%s).", ec.message().c_str());
if (ec != boost::asio::error::operation_aborted) {
pool_->Close(shared_from_this());
}
OnWriteError(ec);
} else {
LOG_INFO("Response has been sent back, length: %u.", length);
// Write the body payload by payload.
response_->body()->InitPayload();
DoWriteBody();
}
}
if (request_->IsConnectionKeepAlive()) {
LOG_INFO("The client asked for a keep-alive connection.");
LOG_INFO("Continue to read the next request...");
Start();
} else {
Shutdown();
pool_->Close(shared_from_this());
}
void Connection::DoWriteBody() {
auto payload = response_->body()->NextPayload();
if (!payload.empty()) {
boost::asio::async_write(socket_, payload,
std::bind(&Connection::OnWriteBody,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
} else {
// No more body payload left, we're done.
OnWriteOK();
}
}
void Connection::OnWriteBody(boost::system::error_code ec, std::size_t length) {
if (ec) {
OnWriteError(ec);
} else {
DoWriteBody();
}
}
void Connection::OnWriteOK() {
LOG_INFO("Response has been sent back.");
if (request_->IsConnectionKeepAlive()) {
LOG_INFO("The client asked for a keep-alive connection.");
LOG_INFO("Continue to read the next request...");
Start();
} else {
Shutdown();
pool_->Close(shared_from_this());
}
}
void Connection::OnWriteError(boost::system::error_code ec) {
LOG_ERRO("Socket write error (%s).", ec.message().c_str());
if (ec != boost::asio::error::operation_aborted) {
pool_->Close(shared_from_this());
}
}