Skip to content

Commit

Permalink
add Network.getTotalUpload, getTotalDownload
Browse files Browse the repository at this point in the history
  • Loading branch information
MihailRis committed Nov 11, 2024
1 parent 46dfdac commit d7389c2
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/network/Network.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata) {

class CurlHttp : public Http {
CURL* curl;

size_t totalUpload = 0;
size_t totalDownload = 0;
public:
CurlHttp(CURL* curl) : curl(curl) {
}
Expand All @@ -33,9 +36,27 @@ class CurlHttp : public Http {
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
long size;
if (!curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &size)) {
totalUpload += size;
}
if (!curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &size)) {
totalDownload += size;
}
totalDownload += buffer.size();
}
callback(res, std::move(buffer));
}

size_t getTotalUpload() const override {
return totalUpload;
}

size_t getTotalDownload() const override {
return totalDownload;
}

static std::unique_ptr<CurlHttp> create() {
if (auto curl = curl_easy_init()) {
return std::make_unique<CurlHttp>(curl);
Expand All @@ -54,6 +75,14 @@ void Network::httpGet(const std::string& url, const OnResponse& callback) {
http->get(url, callback);
}

size_t Network::getTotalUpload() const {
return http->getTotalUpload();
}

size_t Network::getTotalDownload() const {
return http->getTotalDownload();
}

std::unique_ptr<Network> Network::create(const NetworkSettings& settings) {
auto http = CurlHttp::create();
return std::make_unique<Network>(std::move(http));
Expand Down
5 changes: 5 additions & 0 deletions src/network/Network.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ namespace network {
virtual ~Http() {}

virtual void get(const std::string& url, const OnResponse& callback) = 0;
virtual size_t getTotalUpload() const = 0;
virtual size_t getTotalDownload() const = 0;
};

class Network {
Expand All @@ -26,6 +28,9 @@ namespace network {

void httpGet(const std::string& url, const OnResponse& callback);

size_t getTotalUpload() const;
size_t getTotalDownload() const;

static std::unique_ptr<Network> create(const NetworkSettings& settings);
};
}
2 changes: 2 additions & 0 deletions test/network/curltest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ TEST(curltest, curltest) {
std::cout << value << std::endl;
}
);
std::cout << "upload: " << network->getTotalUpload() << " B" << std::endl;
std::cout << "download: " << network->getTotalDownload() << " B" << std::endl;
}

0 comments on commit d7389c2

Please sign in to comment.