Kurlyk
Loading...
Searching...
No Matches
cancel_http_requests.cpp
Go to the documentation of this file.
1#include <kurlyk.hpp>
2
4 if (response->ready) {
5 KURLYK_PRINT << "Response received:" << std::endl
6 << "Status Code: " << response->status_code << std::endl
7 << "Content: " << response->content << std::endl
8 << "----------------------------------------" << std::endl;
9 } else {
10 KURLYK_PRINT << "Response received:" << std::endl
11 << "Request not ready or cancelled." << std::endl
12 << "----------------------------------------" << std::endl;
13 }
14}
15
16int main() {
17 kurlyk::init(true);
18
19 kurlyk::add_error_handler([](const std::exception& ex,
20 const char* func,
21 const char* file,
22 int line,
23 const char* message) {
24 KURLYK_PRINT << "Network error caught:"
25 << "\n Message: " << message
26 << "\n Exception: " << ex.what()
27 << "\n Function: " << func
28 << "\n File: " << file
29 << "\n Line: " << line << std::endl;
30 });
31
32 // Sending a GET request using the first function (callback-based)
33 uint64_t request_id1 = kurlyk::http_get(
34 "https://httpbin.org/delay/5", // Delayed response to simulate long-running request
37 [](kurlyk::HttpResponsePtr response) {
38 KURLYK_PRINT << "Callback-based GET request response:" << std::endl;
39 print_response(response);
40 }
41 );
42
43# if __cplusplus >= 201703L
44 // Sending a GET request using the second function (future-based)
45 auto [request_id2, future_response] = kurlyk::http_get(
46 "https://httpbin.org/delay/5", // Delayed response
49 );
50# else
51 auto func_result = kurlyk::http_get(
52 "https://httpbin.org/delay/5", // Delayed response
55 );
56 uint64_t request_id2 = func_result.first;
57 auto future_response = std::move(func_result.second);
58# endif
59
60 KURLYK_PRINT << "Sent two requests. Request IDs: " << request_id1 << ", " << request_id2 << std::endl;
61
62 // Cancel the first request after a delay
63 std::this_thread::sleep_for(std::chrono::seconds(1));
64 KURLYK_PRINT << "Cancelling the first request (ID: " << request_id1 << ")..." << std::endl;
65 kurlyk::cancel_request_by_id(request_id1, []() {
66 KURLYK_PRINT << "Request 1 cancelled successfully." << std::endl;
67 });
68
69 // Cancel the second request after a delay
70 KURLYK_PRINT << "Cancelling the second request (ID: " << request_id2 << ")..." << std::endl;
71 kurlyk::cancel_request_by_id(request_id2).wait();
72
73 // Ensure all operations complete before exiting
74 try {
75 future_response.get();
76 } catch (const std::exception& e) {
77 KURLYK_PRINT << "Future-based request exception: " << e.what() << std::endl;
78 }
79
80 // ---
81
82 for (int n = 0; n < 10; ++n) {
83 KURLYK_PRINT << "Iteration " << n << std::endl;
84
85 uint32_t limit_id = kurlyk::create_rate_limit_rps(2);
86
87 int num_clients = 10;
88 int num_req = 3;
89 int cancel_after_ms = 3000;
90
91 std::vector<std::unique_ptr<kurlyk::HttpClient>> clients;
92 std::vector<std::future<kurlyk::HttpResponsePtr>> futures;
93
94 for (int i = 0; i < num_clients; ++i) {
95 auto client = std::make_unique<kurlyk::HttpClient>("https://httpbin.org");
96 client->set_timeout(5);
97 client->set_connect_timeout(5);
98 client->set_retry_attempts(3, 1000);
99
100 KURLYK_PRINT << "Client #" << i << std::endl;
101
102 for (int j = 0; j < num_req; ++j) {
103 if (j % 3 == 0) {
104 client->set_head_only(true);
105 futures.emplace_back(client->get("/delay/2", kurlyk::QueryParams(), kurlyk::Headers()));
106 client->set_head_only(false);
107 } else {
108 futures.emplace_back(client->get("/delay/2", kurlyk::QueryParams(), kurlyk::Headers(), limit_id));
109 }
110 }
111 clients.emplace_back(std::move(client));
112 std::this_thread::sleep_for(std::chrono::milliseconds(100));
113 }
114
115 std::this_thread::sleep_for(std::chrono::milliseconds(cancel_after_ms));
116
117 for (int i = 0; i < num_clients; ++i) {
118
119 auto& client = clients[i];
120
121 KURLYK_PRINT << "Client #" << i << " using HEAD request" << std::endl;
122 client->set_head_only(true);
123 futures.emplace_back(client->get("/delay/2", kurlyk::QueryParams(), kurlyk::Headers()));
124 client->set_head_only(false);
125
126 try {
127 KURLYK_PRINT << "[Cancel] Starting cancel for client #" << i << std::endl;
128 client->cancel_requests();
129 KURLYK_PRINT << "[Cancel] Finished cancel for client #" << i << std::endl;
130 } catch (const std::exception& e) {
131 KURLYK_PRINT << "[Cancel] Exception for client #" << i << ": " << e.what() << std::endl;
132 }
133
134 try {
135 KURLYK_PRINT << "[Cancel2] Starting cancel for client #" << i << std::endl;
136 client->cancel_requests();
137 KURLYK_PRINT << "[Cancel2] Finished cancel for client #" << i << std::endl;
138 } catch (const std::exception& e) {
139 KURLYK_PRINT << "[Cancel2] Exception for client #" << i << ": " << e.what() << std::endl;
140 }
141 }
142
143 KURLYK_PRINT << "Results:" << std::endl;
144 for (int i = 0; i < num_clients; ++i) {
145 try {
146 auto response = futures[i].get();
147 KURLYK_PRINT << "[Result] Client #" << i
148 << " | Ready: " << response->ready
149 << " | Status: " << response->status_code
150 << " | Error: " << response->error_code.message()
151 << std::endl;
152 } catch (const std::exception& e) {
153 KURLYK_PRINT << "[Result] Client #" << i << " threw exception: " << e.what() << std::endl;
154 }
155 }
156
157 kurlyk::remove_limit(limit_id);
158 }
159
160 KURLYK_PRINT << "Press Enter to exit..." << std::endl;
161 std::cin.get();
162
164 return 0;
165}
void print_response(const kurlyk::HttpResponsePtr &response)
int main()
Main header file for the Kurlyk library, providing HTTP and WebSocket support.
void init(const bool use_async=true)
Initializes the Kurlyk library, setting up necessary managers and the network worker.
Definition runtime.hpp:13
std::unique_ptr< HttpResponse > HttpResponsePtr
A unique pointer to an HttpResponse object for memory management.
void add_error_handler(::kurlyk::core::NetworkWorker::ErrorHandler handler)
Registers a global error handler for the network worker.
Definition runtime.hpp:44
void deinit()
Deinitializes the Kurlyk library, stopping the network worker and releasing resources.
Definition runtime.hpp:26
utils::CaseInsensitiveMultimap Headers
Alias for HTTP headers, providing a case-insensitive unordered multimap.
long create_rate_limit_rps(long requests_per_second)
Creates a rate limit based on Requests Per Second (RPS).
Definition utils.hpp:29
uint64_t http_get(const std::string &url, const QueryParams &query, const Headers &headers, HttpResponseCallback callback)
Sends an asynchronous HTTP GET request with a callback.
Definition utils.hpp:260
bool remove_limit(long limit_id)
Removes an existing rate limit with the specified identifier.
Definition utils.hpp:37
utils::CaseInsensitiveMultimap QueryParams
Alias for query parameters in HTTP requests, stored case-insensitively.
void cancel_request_by_id(uint64_t request_id, std::function< void()> callback)
Cancels a request by its unique identifier.
Definition utils.hpp:50
#define KURLYK_PRINT