From da2666726e48a3dc00f05589cdf4947f22deb3c3 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Fri, 10 Apr 2020 17:17:16 +0200 Subject: Simplify session handler --- https.cpp | 82 +++++++++++++++++---------------------------------------------- 1 file changed, 22 insertions(+), 60 deletions(-) (limited to 'https.cpp') diff --git a/https.cpp b/https.cpp index 25af275..60f37e7 100644 --- a/https.cpp +++ b/https.cpp @@ -35,20 +35,6 @@ using tcp = boost::asio::ip::tcp; // from namespace { -// This function produces an HTTP response for the given -// request. The type of the response object depends on the -// contents of the request, so the interface requires the -// caller to pass a generic lambda for receiving the response. -template -void -handle_request( - ::Server& server, - request_type&& req, - Send&& send) -{ - return send(std::move(generate_response(req, server))); -} - //------------------------------------------------------------------------------ // Report a failure @@ -81,50 +67,27 @@ fail(beast::error_code ec, char const* what) // Handles an HTTP server connection class session : public std::enable_shared_from_this { - // This is the C++11 equivalent of a generic lambda. - // The function object is used to send an HTTP message. - struct send_lambda - { - session& self_; - - explicit - send_lambda(session& self) - : self_(self) - { - } - - template - void - operator()(http::message&& msg) const - { - // The lifetime of the message has to extend - // for the duration of the async operation so - // we use a shared_ptr to manage it. - auto sp = std::make_shared< - http::message>(std::move(msg)); - - // Store a type-erased version of the shared - // pointer in the class to keep it alive. - self_.res_ = sp; - - // Write the response - http::async_write( - self_.stream_, - *sp, - beast::bind_front_handler( - &session::on_write, - self_.shared_from_this(), - sp->need_eof())); - } - }; - - beast::ssl_stream stream_; - beast::flat_buffer buffer_; - Server& m_server; - http::request req_; - std::shared_ptr res_; - send_lambda lambda_; - + beast::ssl_stream stream_; + beast::flat_buffer buffer_; + Server& m_server; + http::request req_; + std::shared_ptr res_; + + void handle_request(::Server& server, request_type&& req) + { + auto sp = std::make_shared(generate_response(req, server)); + + res_ = sp; + + // Write the response + http::async_write( + stream_, + *sp, + beast::bind_front_handler( + &session::on_write, + shared_from_this(), + sp->need_eof())); + } public: // Take ownership of the socket explicit @@ -134,7 +97,6 @@ public: Server& server) : stream_(std::move(socket), ctx) , m_server(server) - , lambda_(*this) { } @@ -207,7 +169,7 @@ public: return fail(ec, "read"); // Send the response - handle_request(m_server, std::move(req_), lambda_); + handle_request(m_server, std::move(req_)); } void -- cgit v1.2.3