HTTP GET JSON with libcurl timeout
C++
#include <curl/curl.h>
#include <nlohmann/json.hpp>
#include <stdexcept>
#include <string>
static size_t onWrite(char* data, size_t size, size_t n, void* out) {
static_cast<std::string*>(out)->append(data, size * n);
return size * n;
}
nlohmann::json getJson(const std::string& url, long timeoutSec) {
CURL* h = curl_easy_init();
if (!h) throw std::runtime_error("curl init failed");
std::string body;
curl_easy_setopt(h, CURLOPT_URL, url.c_str());
curl_easy_setopt(h, CURLOPT_TIMEOUT, timeoutSec);
curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, onWrite);
curl_easy_setopt(h, CURLOPT_WRITEDATA, &body);
CURLcode rc = curl_easy_perform(h);
curl_easy_cleanup(h);
if (rc != CURLE_OK) throw std::runtime_error(curl_easy_strerror(rc));
return nlohmann::json::parse(body);
}