diff --git a/include/cinatra/coro_http_request.hpp b/include/cinatra/coro_http_request.hpp index cb7ae9a8..2a3edebb 100644 --- a/include/cinatra/coro_http_request.hpp +++ b/include/cinatra/coro_http_request.hpp @@ -248,6 +248,10 @@ class coro_http_request { (aspect_data_.push_back(std::move(args)), ...); } + void set_user_data(std::any data) { user_data_ = std::move(data); } + + std::any get_user_data() { return user_data_; } + std::vector &get_aspect_data() { return aspect_data_; } std::unordered_map get_cookies( @@ -288,6 +292,9 @@ class coro_http_request { if (!aspect_data_.empty()) { aspect_data_.clear(); } + if (user_data_.has_value()) { + user_data_.reset(); + } } std::unordered_map params_; @@ -300,5 +307,6 @@ class coro_http_request { bool is_websocket_ = false; std::vector aspect_data_; std::string cached_session_id_; + std::any user_data_; }; } // namespace cinatra \ No newline at end of file diff --git a/tests/test_cinatra.cpp b/tests/test_cinatra.cpp index ff5e145d..5e3f97c4 100644 --- a/tests/test_cinatra.cpp +++ b/tests/test_cinatra.cpp @@ -547,6 +547,8 @@ TEST_CASE("test request https without init_ssl") { struct add_data { bool before(coro_http_request &req, coro_http_response &res) { req.set_aspect_data("hello world"); + auto val = std::make_shared(42); + req.set_user_data(val); return true; } }; @@ -554,6 +556,13 @@ struct add_data { struct add_more_data { bool before(coro_http_request &req, coro_http_response &res) { req.set_aspect_data(std::vector{"test", "aspect"}); + auto user_data = req.get_user_data(); + CHECK(user_data.has_value()); + auto val = std::any_cast>(user_data); + CHECK(*val == 42); + auto data = req.get_user_data(); + val = std::any_cast>(data); + *val = 43; return true; } }; @@ -570,6 +579,8 @@ struct auth_t { struct dely_t { bool before(coro_http_request &req, coro_http_response &res) { + auto user_data = req.get_user_data(); + CHECK(!user_data.has_value()); res.set_status_and_content(status_type::unauthorized, "unauthorized"); return false; } @@ -603,9 +614,13 @@ TEST_CASE("test aspect") { CHECK(val[0] == "test"); CHECK(val[1] == "aspect"); CHECK(!req.is_upgrade()); + auto user_data = req.get_user_data(); + CHECK(user_data.has_value()); + auto val1 = std::any_cast>(user_data); + CHECK(*val1 == 43); resp.set_status_and_content(status_type::ok, "ok"); }, - add_more_data{}); + add_data{}, add_more_data{}); server.set_http_handler( "/auth", [](coro_http_request &req, coro_http_response &resp) {