Older/Server/HttpSession.h

48 lines
2.0 KiB
C
Raw Normal View History

2023-07-21 16:17:01 +08:00
#ifndef HTTPSESSION_H
#define HTTPSESSION_H
2025-01-10 21:49:22 +08:00
#include "router.hpp"
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/core/tcp_stream.hpp>
#include <boost/beast/http/parser.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/http/write.hpp>
2023-07-21 16:17:01 +08:00
#include <cstdlib>
#include <memory>
#include <optional>
/** Represents an established HTTP connection
*/
class HttpSession : public std::enable_shared_from_this<HttpSession> {
void doRead();
void onWrite(boost::beast::error_code ec, std::size_t, bool close);
public:
using Request = boost::beast::http::request<boost::beast::http::string_body>;
2025-01-10 21:49:22 +08:00
using RequestHandler = std::function<void(HttpSession &, const Request &, const boost::urls::matches &)>;
HttpSession(boost::asio::ip::tcp::socket &&socket, const std::shared_ptr<boost::urls::router<RequestHandler>> &router);
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));
2025-01-07 16:54:07 +08:00
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());
});
2023-07-21 16:17:01 +08:00
}
void errorReply(const Request &request, boost::beast::http::status status, boost::beast::string_view message);
2025-01-07 16:54:07 +08:00
boost::beast::tcp_stream::executor_type executor();
2025-01-10 21:49:22 +08:00
boost::asio::ip::tcp::socket releaseSocket();
2023-07-21 16:17:01 +08:00
void run();
2025-01-10 21:49:22 +08:00
protected:
void onRead(const boost::beast::error_code &error, std::size_t);
2023-07-21 16:17:01 +08:00
private:
boost::beast::tcp_stream m_stream;
2025-01-10 21:49:22 +08:00
std::weak_ptr<boost::urls::router<RequestHandler>> m_router;
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