1+ #include < curl/curl.h>
2+ #include < nlohmann/json.hpp>
3+ #include < string>
4+ #include " utils/logging_utils.h"
5+ #include " utils/result.hpp"
6+ #include " yaml-cpp/yaml.h"
7+
8+ namespace curl_utils {
9+ namespace {
10+ size_t WriteCallback (void * contents, size_t size, size_t nmemb,
11+ std::string* output) {
12+ size_t totalSize = size * nmemb;
13+ output->append ((char *)contents, totalSize);
14+ return totalSize;
15+ }
16+ } // namespace
17+
18+ inline cpp::result<std::string, std::string> SimpleGet (const std::string& url) {
19+ CURL* curl;
20+ CURLcode res;
21+ std::string readBuffer;
22+
23+ // Initialize libcurl
24+ curl_global_init (CURL_GLOBAL_DEFAULT);
25+ curl = curl_easy_init ();
26+
27+ if (!curl) {
28+ return cpp::fail (" Failed to init CURL" );
29+ }
30+ curl_easy_setopt (curl, CURLOPT_URL, url.c_str ());
31+
32+ // Set write function callback and data buffer
33+ curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, WriteCallback);
34+ curl_easy_setopt (curl, CURLOPT_WRITEDATA, &readBuffer);
35+
36+ // Perform the request
37+ res = curl_easy_perform (curl);
38+
39+ if (res != CURLE_OK) {
40+ return cpp::fail (" CURL request failed: " +
41+ static_cast <std::string>(curl_easy_strerror (res)));
42+ }
43+
44+ curl_easy_cleanup (curl);
45+ return readBuffer;
46+ }
47+
48+ inline cpp::result<YAML::Node, std::string> ReadRemoteYaml (
49+ const std::string& url) {
50+ auto result = SimpleGet (url);
51+ if (result.has_error ()) {
52+ return cpp::fail (result.error ());
53+ }
54+
55+ try {
56+ return YAML::Load (result.value ());
57+ } catch (const std::exception& e) {
58+ return cpp::fail (" YAML from " + url +
59+ " parsing error: " + std::string (e.what ()));
60+ }
61+ }
62+
63+ inline cpp::result<nlohmann::json, std::string> SimpleGetJson (
64+ const std::string& url) {
65+ auto result = SimpleGet (url);
66+ if (result.has_error ()) {
67+ return cpp::fail (result.error ());
68+ }
69+
70+ try {
71+ return nlohmann::json::parse (result.value ());
72+ } catch (const std::exception& e) {
73+ return cpp::fail (" JSON from " + url +
74+ " parsing error: " + std::string (e.what ()));
75+ }
76+ }
77+ } // namespace curl_utils
0 commit comments