72 auto self(this->shared_from_this());
74 auto data(std::make_shared<boost::asio::streambuf>());
77 boost::asio::async_read_until(
81 [self, data](
const boost::system::error_code& e, std::size_t n) {
83 std::cout <<
"error in HttpServer::Connection#_readHeader: " << e << std::endl;
87 boost::asio::streambuf::const_buffers_type bufs = data->data();
88 std::string dataAsString(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + n);
90 auto headers(std::make_shared<std::unordered_map<std::string, std::string>>(self->_httpParser.parseHeader(dataAsString,
true)));
92 unsigned long long size;
93 auto contentLengthIter = headers->find(
"Content-Length");
94 if (contentLengthIter != headers->end()) {
95 size = std::stoull(contentLengthIter->second);
101 std::string answer = self->_httpParser.generateResponse(
"Bad request",
"text/plain", 400,
"Bad request",
false);
102 boost::asio::async_write(
104 boost::asio::buffer(answer),
105 [](
const boost::system::error_code&, std::size_t) { });
110 self->_readBody(data, size, headers);
114 void _readBody(std::shared_ptr<boost::asio::streambuf> data,
unsigned long long size, std::shared_ptr<std::unordered_map<std::string, std::string>> headers) {
115 auto self(this->shared_from_this());
119 boost::asio::async_read(
_socket,
121 boost::asio::transfer_exactly(size - data->size()),
122 [self, data, size, headers](
const boost::system::error_code& e, std::size_t) {
124 std::cout <<
"error in HttpServer::Connection#_readBody: " << e << std::endl;
128 boost::asio::streambuf::const_buffers_type bufs = data->data();
129 std::string dataAsString(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + size);
133 answer = self->_handler(dataAsString, *headers);
134 }
catch (std::exception& e) {
135 std::cout <<
"error in HttpServer::Connection#_readBody answer: " << e.what() << std::endl;
136 answer = self->_httpParser.generateResponse(
"Internal server error",
"text/plain", 500,
"Internal server error",
false);
138 boost::asio::async_write(
140 boost::asio::buffer(answer),
141 [](
const boost::system::error_code&, std::size_t) { });
143 self->_socket.close();