Older/Server/HttpSession.h

41 lines
1.5 KiB
C
Raw Permalink Normal View History

2023-07-21 16:17:01 +08:00
#ifndef HTTPSESSION_H
#define HTTPSESSION_H
#include "boost/beast.hpp"
#include <cstdlib>
#include <memory>
#include <optional>
/** Represents an established HTTP connection
*/
class HttpSession : public std::enable_shared_from_this<HttpSession> {
void doRead();
void onRead(boost::beast::error_code ec, std::size_t);
void onWrite(boost::beast::error_code ec, std::size_t, bool close);
// void sendResponse(boost::beast::http::response<boost::beast::http::string_body> &&response);
public:
using Request = boost::beast::http::request<boost::beast::http::string_body>;
2024-01-24 23:19:53 +08:00
HttpSession(boost::asio::ip::tcp::socket &&socket);
2023-07-21 16:17:01 +08:00
template <typename Response>
2023-12-31 01:13:26 +08:00
void reply(Response &&response) {
2023-07-21 16:17:01 +08:00
using ResponseType = typename std::decay_t<decltype(response)>;
auto sp = std::make_shared<ResponseType>(std::forward<decltype(response)>(response));
boost::beast::http::async_write(
m_stream, *sp, [self = shared_from_this(), sp](boost::beast::error_code ec, std::size_t bytes) {
self->onWrite(ec, bytes, sp->need_eof());
});
}
void errorReply(const Request &request, boost::beast::http::status status, boost::beast::string_view message);
void run();
private:
boost::beast::tcp_stream m_stream;
2024-01-02 12:10:35 +08:00
boost::beast::flat_buffer m_buffer{std::numeric_limits<std::uint32_t>::max()};
2023-07-21 16:17:01 +08:00
std::optional<boost::beast::http::request_parser<boost::beast::http::string_body>> m_parser;
};
#endif // HTTPSESSION_H