-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path01_http_client.cpp
More file actions
68 lines (60 loc) · 2.03 KB
/
Copy path01_http_client.cpp
File metadata and controls
68 lines (60 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <HXLibs/net/client/HttpClient.hpp>
#include <HXLibs/net/ApiMacro.hpp>
#include <HXLibs/log/Log.hpp>
using namespace HX;
using namespace net;
using namespace container;
coroutine::Task<> coMain() {
HttpClient cli{};
log::hxLog.debug("开始请求");
auto res = (co_await cli.coGet("http://127.0.0.1:28205/get")).move();
log::hxLog.info("状态码:", res.status);
log::hxLog.info("拿到了 头:", res.headers);
log::hxLog.info("拿到了 体:", res.body);
}
int main() {
HttpServer server{28205};
server.addEndpoint<GET>("/get", [] ENDPOINT {
std::string json;
reflection::toJson(req.getHeaders(), json);
co_await res.setStatusAndContent(Status::CODE_400, std::move(json))
.sendRes();
});
server.asyncRun<decltype(1_s)>(1);
coroutine::EventLoop loop;
loop.sync(coMain());
HttpClient cli{};
auto t = cli.get("http://127.0.0.1:28205/get").get();
do {
if (!t) [[unlikely]] {
log::hxLog.error("coMain:", t.what());
break;
}
auto res = t.move();
log::hxLog.info("状态码:", res.status);
log::hxLog.info("拿到了 头:", res.headers);
log::hxLog.info("拿到了 体:", res.body);
} while (false);
// 支持异步 API thenTry(Try<T>)
cli.get("http://127.0.0.1:28205/get").thenTry([](Try<ResponseData> resTry) {
if (resTry) {
auto res = resTry.move();
log::hxLog.info("状态码:", res.status);
log::hxLog.info("拿到了 头:", res.headers);
log::hxLog.info("拿到了 体:", res.body);
} else {
log::hxLog.error("发生异常:", resTry.what());
}
return resTry;
}).thenTry([](auto t) {
if (!t) [[unlikely]] {
log::hxLog.error("coMain:", t.what());
return;
}
auto res = t.move();
log::hxLog.info("期望是空的:", res); // 应该是空的
}).wait();
cli.close();
log::hxLog.debug("end");
return 0;
}