cofetch
Chainable, high-performance async HTTP client for C++ event loops
Loading...
Searching...
No Matches
example_coroutine.cpp

Dependent requests in linear code with C++20 co_await.

Dependent requests in linear code with C++20 co_await.

// Dependent requests in linear code with co_await (C++20).
#include <cofetch.h>
#include <asio.hpp>
#include <iostream>
asio::awaitable<void> fetch_then_post(cofetch::Client& http) {
// First request: ask the server for its time.
const auto time = co_await http.async_get(
"https://fapi.binance.com/fapi/v1/time", asio::use_awaitable);
std::cout << "server time: " << time.data_ << "\n";
// Second request uses the first one's result — still top to bottom,
// no callback nesting.
const auto echo = co_await http.request("https://postman-echo.com/post")
.body("prev=" + time.data_)
.post(asio::use_awaitable);
std::cout << "echo: http " << echo.http_code_ << "\n";
}
int main() {
asio::io_context io;
cofetch::Client http(io);
asio::co_spawn(io, fetch_then_post(http), asio::detached);
io.run();
}
auto post(CompletionToken &&token)
Definition cofetch.h:377
RequestBuilder & body(std::string b)
Definition cofetch.h:354
Definition cofetch.h:266
RequestBuilder request(std::string url)
Start a fluent request chain: request(url).body(...).post(token).
Definition cofetch.h:412
auto async_get(std::string url, CompletionToken &&token)
Definition cofetch.h:324