Skip to content

Commit

Permalink
fix aspect
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos committed Dec 16, 2024
1 parent 3584a05 commit 75c218d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
11 changes: 5 additions & 6 deletions include/cinatra/coro_http_router.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ class coro_http_router {
if (ok) {
co_await handler(req, resp);
}
ok = true;
(do_after(asps, req, resp, ok), ...);
};
}
Expand Down Expand Up @@ -113,6 +114,7 @@ class coro_http_router {
if (ok) {
handler(req, resp);
}
ok = true;
(do_after(asps, req, resp, ok), ...);
};
}
Expand Down Expand Up @@ -155,20 +157,17 @@ class coro_http_router {
}
ok = aspect.before(req, resp);
}
else {
ok = true;
}
}

template <typename T>
void do_after(T& aspect, coro_http_request& req, coro_http_response& resp,
bool& ok) {
if constexpr (has_after_v<T>) {
if (!ok) {
return;
}
ok = aspect.after(req, resp);
}
else {
ok = true;
}
}

std::function<void(coro_http_request& req, coro_http_response& resp)>*
Expand Down
20 changes: 19 additions & 1 deletion tests/test_cinatra.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -558,15 +558,32 @@ struct add_more_data {
}
};

std::vector<std::string> 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 {
bool before(coro_http_request &req, coro_http_response &res) {
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") {
Expand Down Expand Up @@ -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<GET>(
"/exception", [](coro_http_request &req, coro_http_response &resp) {
throw std::invalid_argument("invalid argument");
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 75c218d

Please sign in to comment.