From 75c218df2f57b8bffc4e30673f927b6c13561e8f Mon Sep 17 00:00:00 2001 From: qicosmos Date: Mon, 16 Dec 2024 10:55:12 +0800 Subject: [PATCH] fix aspect --- include/cinatra/coro_http_router.hpp | 11 +++++------ tests/test_cinatra.cpp | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/include/cinatra/coro_http_router.hpp b/include/cinatra/coro_http_router.hpp index 2d4d8293..76b0cb06 100644 --- a/include/cinatra/coro_http_router.hpp +++ b/include/cinatra/coro_http_router.hpp @@ -66,6 +66,7 @@ class coro_http_router { if (ok) { co_await handler(req, resp); } + ok = true; (do_after(asps, req, resp, ok), ...); }; } @@ -113,6 +114,7 @@ class coro_http_router { if (ok) { handler(req, resp); } + ok = true; (do_after(asps, req, resp, ok), ...); }; } @@ -155,20 +157,17 @@ class coro_http_router { } ok = aspect.before(req, resp); } - else { - ok = true; - } } template void do_after(T& aspect, coro_http_request& req, coro_http_response& resp, bool& ok) { if constexpr (has_after_v) { + if (!ok) { + return; + } ok = aspect.after(req, resp); } - else { - ok = true; - } } std::function* diff --git a/tests/test_cinatra.cpp b/tests/test_cinatra.cpp index a9aa6e3e..b29f75f3 100644 --- a/tests/test_cinatra.cpp +++ b/tests/test_cinatra.cpp @@ -558,8 +558,14 @@ struct add_more_data { } }; +std::vector aspect_test_vec; + struct auth_t { bool before(coro_http_request &req, coro_http_response &res) { return true; } + bool after(coro_http_request &req, coro_http_response &res) { + aspect_test_vec.push_back("enter auth_t after"); + return false; + } }; struct dely_t { @@ -567,6 +573,17 @@ struct dely_t { res.set_status_and_content(status_type::unauthorized, "unauthorized"); return false; } + bool after(coro_http_request &req, coro_http_response &res) { + aspect_test_vec.push_back("enter delay_t after"); + return true; + } +}; + +struct another_t { + bool after(coro_http_request &req, coro_http_response &res) { + // won't comming + return true; + } }; TEST_CASE("test aspect") { @@ -594,7 +611,7 @@ TEST_CASE("test aspect") { [](coro_http_request &req, coro_http_response &resp) { resp.set_status_and_content(status_type::ok, "ok"); }, - dely_t{}, auth_t{}); + dely_t{}, auth_t{}, another_t{}); server.set_http_handler( "/exception", [](coro_http_request &req, coro_http_response &resp) { throw std::invalid_argument("invalid argument"); @@ -628,6 +645,7 @@ TEST_CASE("test aspect") { CHECK(result.status == 200); result = async_simple::coro::syncAwait(client.async_get("/auth")); CHECK(result.status == 401); + CHECK(aspect_test_vec.size() == 2); CHECK(result.resp_body == "unauthorized"); result = async_simple::coro::syncAwait(client.async_get("/exception")); CHECK(result.status == 503);