Line data Source code
1 : #ifndef THINGER_HTTP_CLIENT_STREAM_TYPES_HPP
2 : #define THINGER_HTTP_CLIENT_STREAM_TYPES_HPP
3 :
4 : #include <string>
5 : #include <string_view>
6 : #include <functional>
7 : #include <map>
8 :
9 : namespace thinger::http {
10 :
11 : /**
12 : * Information passed to stream callbacks for each chunk of data.
13 : */
14 : struct stream_info {
15 : std::string_view data; // Current chunk data
16 : size_t downloaded; // Total bytes downloaded so far
17 : size_t total; // Total expected size (0 if unknown, e.g., chunked)
18 : int status_code; // HTTP status code
19 : };
20 :
21 : /**
22 : * Result of a streaming operation.
23 : */
24 : struct stream_result {
25 : int status_code = 0;
26 : std::string error; // Empty if no connection error
27 : std::map<std::string, std::string> headers; // Response headers
28 : size_t bytes_transferred = 0;
29 :
30 : /**
31 : * Returns true if the request succeeded (no error and 2xx status).
32 : */
33 18 : bool ok() const {
34 18 : return error.empty() && status_code >= 200 && status_code < 300;
35 : }
36 :
37 : /**
38 : * Conversion to bool for if(result) checks.
39 : */
40 8 : explicit operator bool() const { return ok(); }
41 :
42 : /**
43 : * Returns true if the request completed (even if status is not 2xx).
44 : * Use this to distinguish between network errors and HTTP errors.
45 : */
46 8 : bool completed() const { return error.empty() && status_code > 0; }
47 :
48 : /**
49 : * Returns true if there was a network/connection error.
50 : */
51 6 : bool has_network_error() const { return !error.empty(); }
52 :
53 : /**
54 : * Returns true if the server returned an error status (4xx or 5xx).
55 : */
56 6 : bool has_http_error() const {
57 6 : return error.empty() && status_code >= 400;
58 : }
59 : };
60 :
61 : /**
62 : * Callback for streaming data.
63 : * Called for each chunk of data received.
64 : * Return true to continue, false to abort the download.
65 : */
66 : using stream_callback = std::function<bool(const stream_info&)>;
67 :
68 : /**
69 : * Callback for download progress.
70 : * @param downloaded Bytes downloaded so far
71 : * @param total Total bytes expected (0 if unknown)
72 : */
73 : using progress_callback = std::function<void(size_t downloaded, size_t total)>;
74 :
75 : } // namespace thinger::http
76 :
77 : #endif // THINGER_HTTP_CLIENT_STREAM_TYPES_HPP
|