// // requester.cpp // curly // // Created by Bob Polis at 2020-09-01 // Copyright (c) 2020 SwiftCoder. All rights reserved. // #include "requester.hpp" #include #include #include #include extern sc::logger logger; size_t requester::write_data(char *buf, size_t sz, size_t nmemb, void *user_data) { size_t realsize = sz * nmemb; SCInfo(logger, "received ", realsize, " bytes"); std::vector* dest {reinterpret_cast*>(user_data)}; size_t oldsize = dest->size(); dest->resize(oldsize + realsize); std::memcpy(dest->data() + oldsize, buf, realsize); return realsize; } requester::requester() { curl_global_init(CURL_GLOBAL_ALL); _h = curl_easy_init(); curl_easy_setopt(_h, CURLOPT_WRITEFUNCTION, write_data); } requester::~requester() { if (_h) { curl_easy_cleanup(_h); } } requester::requester(requester&& other) { _h = other._h; other._h = nullptr; } requester& requester::operator=(requester &&other) { if (this != &other) { if (_h) { curl_easy_cleanup(_h); } _h = other._h; other._h = nullptr; } return *this; } std::string requester::get(const std::string &url) { curl_easy_setopt(_h, CURLOPT_URL, url.c_str()); std::vector buf; curl_easy_setopt(_h, CURLOPT_WRITEDATA, &buf); auto success = curl_easy_perform(_h); if (success != CURLE_OK) throw std::runtime_error("could not get remote data"); std::string text {buf.data(), buf.size()}; return text; }