Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update doc and coro io #558

Merged
merged 4 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 2 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,26 +456,15 @@ async_simple::coro::Lazy<void> test_download() {
```c++
async_simple::coro::Lazy<void> test_websocket() {
coro_http_client client{};
client.on_ws_close([](std::string_view reason) {
std::cout << "web socket close " << reason << std::endl;
});
client.on_ws_msg([](resp_data data) {
if (data.net_err) {
std::cout << data.net_err.message() << "\n";
return;
}
std::cout << data.resp_body << std::endl;
});

auto r = co_await client.connect("ws://localhost:8090/ws");
if (r.net_err) {
co_return;
}

co_await client.write_websocket("hello websocket"); // mask as default.
co_await client.write_websocket("hello websocket");
auto data = co_await client.read_websocket();
CHECK(data.resp_body == "hello websocket");
co_await client.write_websocket("test again", /*need_mask = */ false);
co_await client.write_websocket("test again");
data = co_await client.read_websocket();
CHECK(data.resp_body == "test again");
co_await client.write_websocket("ws close");
Expand Down
3 changes: 1 addition & 2 deletions example/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,7 @@ async_simple::coro::Lazy<void> use_websocket() {
co_return;
}

auto result =
co_await client.write_websocket("hello websocket"); // mask as default.
auto result = co_await client.write_websocket("hello websocket");
assert(!result.net_err);
auto data = co_await client.read_websocket();
assert(data.resp_body == "hello websocket");
Expand Down
123 changes: 68 additions & 55 deletions include/cinatra/coro_http_connection.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -192,78 +192,84 @@ class coro_http_connection
co_await router_.route_coro(coro_handler, request_, response_, key);
}
else {
bool is_exist = false;
std::function<void(coro_http_request & req,
coro_http_response & resp)>
handler;
std::string method_str{parser_.method()};
std::string url_path = method_str;
url_path.append(" ").append(parser_.url());
std::tie(is_exist, handler, request_.params_) =
router_.get_router_tree()->get(url_path, method_str);
if (is_exist) {
if (handler) {
(handler)(request_, response_);
}
else {
response_.set_status(status_type::not_found);
}
if (default_handler_) {
default_handler_(request_, response_);
}
else {
bool is_coro_exist = false;
std::function<async_simple::coro::Lazy<void>(
coro_http_request & req, coro_http_response & resp)>
coro_handler;

std::tie(is_coro_exist, coro_handler, request_.params_) =
router_.get_coro_router_tree()->get_coro(url_path, method_str);

if (is_coro_exist) {
if (coro_handler) {
co_await coro_handler(request_, response_);
bool is_exist = false;
std::function<void(coro_http_request & req,
coro_http_response & resp)>
handler;
std::string method_str{parser_.method()};
std::string url_path = method_str;
url_path.append(" ").append(parser_.url());
std::tie(is_exist, handler, request_.params_) =
router_.get_router_tree()->get(url_path, method_str);
if (is_exist) {
if (handler) {
(handler)(request_, response_);
}
else {
response_.set_status(status_type::not_found);
}
}
else {
bool is_matched_regex_router = false;
// coro regex router
auto coro_regex_handlers = router_.get_coro_regex_handlers();
if (coro_regex_handlers.size() != 0) {
for (auto &pair : coro_regex_handlers) {
std::string coro_regex_key{key};

if (std::regex_match(coro_regex_key, request_.matches_,
std::get<0>(pair))) {
auto coro_handler = std::get<1>(pair);
if (coro_handler) {
co_await coro_handler(request_, response_);
is_matched_regex_router = true;
}
}
bool is_coro_exist = false;
std::function<async_simple::coro::Lazy<void>(
coro_http_request & req, coro_http_response & resp)>
coro_handler;

std::tie(is_coro_exist, coro_handler, request_.params_) =
router_.get_coro_router_tree()->get_coro(url_path,
method_str);

if (is_coro_exist) {
if (coro_handler) {
co_await coro_handler(request_, response_);
}
else {
response_.set_status(status_type::not_found);
}
}
// regex router
if (!is_matched_regex_router) {
auto regex_handlers = router_.get_regex_handlers();
if (regex_handlers.size() != 0) {
for (auto &pair : regex_handlers) {
std::string regex_key{key};
if (std::regex_match(regex_key, request_.matches_,
else {
bool is_matched_regex_router = false;
// coro regex router
auto coro_regex_handlers = router_.get_coro_regex_handlers();
if (coro_regex_handlers.size() != 0) {
for (auto &pair : coro_regex_handlers) {
std::string coro_regex_key{key};

if (std::regex_match(coro_regex_key, request_.matches_,
std::get<0>(pair))) {
auto handler = std::get<1>(pair);
if (handler) {
(handler)(request_, response_);
auto coro_handler = std::get<1>(pair);
if (coro_handler) {
co_await coro_handler(request_, response_);
is_matched_regex_router = true;
}
}
}
}
// regex router
if (!is_matched_regex_router) {
auto regex_handlers = router_.get_regex_handlers();
if (regex_handlers.size() != 0) {
for (auto &pair : regex_handlers) {
std::string regex_key{key};
if (std::regex_match(regex_key, request_.matches_,
std::get<0>(pair))) {
auto handler = std::get<1>(pair);
if (handler) {
(handler)(request_, response_);
is_matched_regex_router = true;
}
}
}
}
}
// not found
if (!is_matched_regex_router)
response_.set_status(status_type::not_found);
}
// not found
if (!is_matched_regex_router)
response_.set_status(status_type::not_found);
}
}
}
Expand Down Expand Up @@ -407,6 +413,11 @@ class coro_http_connection

void set_multi_buf(bool r) { multi_buf_ = r; }

void set_default_handler(
std::function<void(coro_http_request &, coro_http_response &)> &handler) {
default_handler_ = handler;
}

async_simple::coro::Lazy<bool> write_data(std::string_view message) {
std::vector<asio::const_buffer> buffers;
buffers.push_back(asio::buffer(message));
Expand Down Expand Up @@ -834,5 +845,7 @@ class coro_http_connection
#endif
bool need_shrink_every_time_ = false;
bool multi_buf_ = true;
std::function<void(coro_http_request &, coro_http_response &)>
default_handler_ = nullptr;
};
} // namespace cinatra
10 changes: 10 additions & 0 deletions include/cinatra/coro_http_server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,11 @@ class coro_http_server {

void set_shrink_to_fit(bool r) { need_shrink_every_time_ = r; }

void set_default_handler(
std::function<void(coro_http_request &, coro_http_response &)> handler) {
default_handler_ = std::move(handler);
}

size_t connection_count() {
std::scoped_lock lock(conn_mtx_);
return connections_.size();
Expand Down Expand Up @@ -655,6 +660,9 @@ class coro_http_server {
if (need_check_) {
conn->set_check_timeout(true);
}
if (default_handler_) {
conn->set_default_handler(default_handler_);
}

#ifdef CINATRA_ENABLE_SSL
if (use_ssl_) {
Expand Down Expand Up @@ -915,6 +923,8 @@ class coro_http_server {
#endif
coro_http_router router_;
bool need_shrink_every_time_ = false;
std::function<void(coro_http_request &, coro_http_response &)>
default_handler_ = nullptr;
};

using http_server = coro_http_server;
Expand Down
10 changes: 5 additions & 5 deletions include/cinatra/ylt/coro_io/coro_io.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class callback_awaitor_base {
template <typename Op>
class callback_awaitor_impl {
public:
callback_awaitor_impl(Derived &awaitor, const Op &op) noexcept
callback_awaitor_impl(Derived &awaitor, Op &op) noexcept
: awaitor(awaitor), op(op) {}
constexpr bool await_ready() const noexcept { return false; }
void await_suspend(std::coroutine_handle<> handle) noexcept {
Expand All @@ -59,7 +59,7 @@ class callback_awaitor_base {

private:
Derived &awaitor;
const Op &op;
Op &op;
};

public:
Expand Down Expand Up @@ -87,7 +87,7 @@ class callback_awaitor_base {
Derived *obj;
};
template <typename Op>
callback_awaitor_impl<Op> await_resume(const Op &op) noexcept {
callback_awaitor_impl<Op> await_resume(Op &&op) noexcept {
return callback_awaitor_impl<Op>{static_cast<Derived &>(*this), op};
}

Expand Down Expand Up @@ -289,7 +289,7 @@ inline async_simple::coro::Lazy<void> sleep_for(const Duration &d,
co_await timer.async_await();
}
template <typename Duration>
inline async_simple::coro::Lazy<void> sleep_for(const Duration &d) {
inline async_simple::coro::Lazy<void> sleep_for(Duration d) {
if (auto executor = co_await async_simple::CurrentExecutor();
executor != nullptr) {
co_await async_simple::coro::sleep(d);
Expand All @@ -302,7 +302,7 @@ inline async_simple::coro::Lazy<void> sleep_for(const Duration &d) {

template <typename R, typename Func, typename Executor>
struct post_helper {
void operator()(auto handler) const {
void operator()(auto handler) {
asio::dispatch(e, [this, handler]() {
try {
if constexpr (std::is_same_v<R, async_simple::Try<void>>) {
Expand Down
8 changes: 3 additions & 5 deletions lang/coro_http_client_introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -423,13 +423,13 @@ auto r = async_simple::coro::syncAwait(
```
# websocket
websocket 的支持需要3步:
- 设置读websocket 数据的回调函数;
- 连接服务器;
- 发送websocket 数据;
- 读websocket 数据;

设置websocket 读数据接口:
websocket 读数据接口:
```c++
void on_ws_msg(std::function<void(resp_data)> on_ws_msg);
async_simple::coro::Lazy<resp_data> read_websocket();
```
websocket 连接服务器接口:
```c++
Expand Down Expand Up @@ -458,10 +458,8 @@ enum opcode : std::uint8_t {

/// 发送websocket 数据
/// \param msg 要发送的websocket 数据
/// \param need_mask 是否需要对数据进行mask,默认会mask
/// \param op opcode 一般为text、binary或 close 等类型
async_simple::coro::Lazy<resp_data> write_websocket(std::string msg,
bool need_mask = true,
opcode op = opcode::text);
```

Expand Down
15 changes: 2 additions & 13 deletions lang/english/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -414,26 +414,15 @@ async_simple::coro::Lazy<void> test_download() {
```c++
async_simple::coro::Lazy<void> test_websocket() {
coro_http_client client{};
client.on_ws_close([](std::string_view reason) {
std::cout << "web socket close " << reason << std::endl;
});
client.on_ws_msg([](resp_data data) {
if (data.net_err) {
std::cout << data.net_err.message() << "\n";
return;
}
std::cout << data.resp_body << std::endl;
});

auto r = co_await client.connect("ws://localhost:8090/ws");
if (r.net_err) {
co_return;
}

co_await client.write_websocket("hello websocket"); // mask as default.
co_await client.write_websocket("hello websocket");
auto data = co_await client.read_websocket();
CHECK(data.resp_body == "hello websocket");
co_await client.write_websocket("test again", /*need_mask = */ false);
co_await client.write_websocket("test again");
data = co_await client.read_websocket();
CHECK(data.resp_body == "test again");
co_await client.write_websocket("ws close");
Expand Down
20 changes: 20 additions & 0 deletions tests/test_cinatra.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,26 @@ async_simple::coro::Lazy<void> test_collect_all() {
thd.join();
}

TEST_CASE("test default http handler") {
coro_http_server server(1, 9001);
server.set_default_handler([](coro_http_request &req,
coro_http_response &resp) {
resp.set_status_and_content(status_type::ok, "It is from default handler");
});
server.async_start();

for (int i = 0; i < 5; i++) {
coro_http_client client{};
async_simple::coro::syncAwait(client.connect("http://127.0.0.1:9001"));
auto data = client.get("/test");
CHECK(data.resp_body == "It is from default handler");
data = client.get("/test_again");
CHECK(data.resp_body == "It is from default handler");
data = client.get("/any");
CHECK(data.resp_body == "It is from default handler");
}
}

TEST_CASE("test request with out buffer") {
std::string str;
str.resize(10);
Expand Down
Loading