Originally posted by sdack
View Post

Code:
#include <iostream> #include <curl/curl.h> #include <nlohmann/json.hpp> #include <functional> using json = nlohmann::json;
Code:
// Callback function to handle data received from libcurl size_t WriteCallback(char* contents, size_t size, size_t nmemb, std::string* out) { if (contents==nullptr || out==nullptr) { std::cerr << "Error: Null pointer passed to WriteCallback" << std::endl; return 0; } size_t totalSize = size * nmemb; if (totalSize == 0) { std::cerr << "Error: Received empty data (size=0)" << std::endl; return 0; } // Append data to the output buffer //out->append(data, totalSize); out->append(contents, totalSize); return totalSize; } void fetch(const std::string& url, const std::function<void(const json&)>& callback) { if (url.empty()) { std::cerr << "Error: Empty URL provided" << std::endl; return; } if (callback == nullptr) { std::cerr << "Error: Null callback function provided" << std::endl; return; } CURL* curl = nullptr; CURLcode res; std::string readBuffer; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl == nullptr) { std::cerr << "Error: Failed to initialize CURL" << std::endl; return; } curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); res = curl_easy_perform(curl); if (res != CURLE_OK) { std::cerr << "Failed to fetch " << url << ": " << curl_easy_strerror(res) << std::endl; } else { // Check if readBuffer is empty (size 0) before attempting to parse if (readBuffer.empty()) { std::cerr << "Error: Received empty response body from " << url << std::endl; } else { try { json jsonData = json::parse(readBuffer); callback(jsonData); } catch (const json::parse_error& e) { std::cerr << "Failed to decode JSON from " << url << ": " << e.what() << std::endl; } } } curl_easy_cleanup(curl); curl_global_cleanup(); }
Code:
int main() { fetch("http://worldtimeapi.org/api/ip", [](const json& data) { if (data.is_null()) { std::cerr << "Error: Received null JSON data" << std::endl; return; } std::cout << "Received data " << data.dump(4) << std::endl; }); return 0; }
A most compressed source code can be difficult to handle without also descriptive comments (and that's before the compiler&build system or at least the interpreter (~Perl or Python, byte-code or IL) translates to machine code)?
(thx) ]
Comment