Skip to content

Commit ad5fba4

Browse files
authored
Merge pull request #23 from underscorediscovery/progress-callback
add progress callback for http clients
2 parents ec34abb + 45d79d1 commit ad5fba4

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

httplib.h

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ namespace httplib
7070
typedef std::map<std::string, std::string> Map;
7171
typedef std::multimap<std::string, std::string> MultiMap;
7272
typedef std::smatch Match;
73+
typedef std::function<void (int64_t current, int64_t total)> Progress;
7374

7475
struct Request {
7576
std::string method;
@@ -78,6 +79,7 @@ struct Request {
7879
std::string body;
7980
Map params;
8081
Match matches;
82+
Progress progress;
8183

8284
bool has_header(const char* key) const;
8385
std::string get_header_value(const char* key) const;
@@ -169,7 +171,7 @@ class Client {
169171
Client(const char* host, int port);
170172
virtual ~Client();
171173

172-
std::shared_ptr<Response> get(const char* path);
174+
std::shared_ptr<Response> get(const char* path, Progress callback = [](int64_t,int64_t){});
173175
std::shared_ptr<Response> head(const char* path);
174176
std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
175177
std::shared_ptr<Response> post(const char* path, const Map& params);
@@ -511,7 +513,7 @@ inline bool read_headers(Stream& strm, MultiMap& headers)
511513
}
512514

513515
template <typename T>
514-
bool read_content(Stream& strm, T& x, bool allow_no_content_length)
516+
bool read_content(Stream& strm, T& x, bool allow_no_content_length, Progress progress = [](int64_t,int64_t){})
515517
{
516518
auto len = get_header_value_int(x.headers, "Content-Length", 0);
517519
if (len) {
@@ -523,6 +525,7 @@ bool read_content(Stream& strm, T& x, bool allow_no_content_length)
523525
return false;
524526
}
525527
r += r_incr;
528+
progress(r, len);
526529
}
527530
} else if (allow_no_content_length) {
528531
for (;;) {
@@ -1087,7 +1090,7 @@ inline bool Client::process_request(Stream& strm, const Request& req, Response&
10871090
return false;
10881091
}
10891092
if (req.method != "HEAD") {
1090-
if (!detail::read_content(strm, res, true)) {
1093+
if (!detail::read_content(strm, res, true, req.progress)) {
10911094
return false;
10921095
}
10931096
}
@@ -1109,11 +1112,12 @@ inline void Client::add_default_headers(Request& req)
11091112
req.set_header("User-Agent", "cpp-httplib/0.1");
11101113
}
11111114

1112-
inline std::shared_ptr<Response> Client::get(const char* path)
1115+
inline std::shared_ptr<Response> Client::get(const char* path, Progress callback)
11131116
{
11141117
Request req;
11151118
req.method = "GET";
11161119
req.path = path;
1120+
req.progress = callback;
11171121
add_default_headers(req);
11181122

11191123
auto res = std::make_shared<Response>();

0 commit comments

Comments
 (0)