58 lines
2.0 KiB
C++
58 lines
2.0 KiB
C++
#include "requester.hpp"
|
|
#include <curl/curl.h>
|
|
#include <vector>
|
|
#include <cstring>
|
|
#include <stdexcept>
|
|
#include <libsclogging.hpp>
|
|
|
|
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::string* text {reinterpret_cast<std::string*>(user_data)};
|
|
text->append(buf, realsize);
|
|
return realsize;
|
|
}
|
|
|
|
requester::requester() {
|
|
curl_global_init(CURL_GLOBAL_ALL);
|
|
_h.reset(curl_easy_init());
|
|
curl_easy_setopt(_h.get(), CURLOPT_WRITEFUNCTION, write_data);
|
|
}
|
|
|
|
requester::~requester() {
|
|
curl_global_cleanup();
|
|
}
|
|
|
|
std::string requester::get(const std::string &url) {
|
|
std::string text;
|
|
curl_easy_setopt(_h.get(), CURLOPT_URL, url.c_str());
|
|
curl_easy_setopt(_h.get(), CURLOPT_WRITEDATA, &text);
|
|
auto success = curl_easy_perform(_h.get());
|
|
if (success != CURLE_OK) throw std::runtime_error("could not get remote data");
|
|
long status;
|
|
success = curl_easy_getinfo(_h.get(), CURLINFO_RESPONSE_CODE, &status);
|
|
if (success != CURLE_OK || status != 200) throw std::runtime_error("could not get remote data");
|
|
return text;
|
|
}
|
|
|
|
std::string requester::post(const std::string& url, const std::string& json) {
|
|
curl_easy_setopt(_h.get(), CURLOPT_URL, url.c_str());
|
|
curl_easy_setopt(_h.get(), CURLOPT_POST, 1L);
|
|
curl_easy_setopt(_h.get(), CURLOPT_POSTFIELDS, json.c_str());
|
|
curl_easy_setopt(_h.get(), CURLOPT_POSTFIELDSIZE, json.size());
|
|
|
|
struct curl_slist* headers {nullptr};
|
|
headers = curl_slist_append(headers, "Content-Type: application/json");
|
|
std::unique_ptr<struct curl_slist, void(*)(struct curl_slist*)> hdrs {headers, curl_slist_free_all};
|
|
curl_easy_setopt(_h.get(), CURLOPT_HTTPHEADER, headers);
|
|
|
|
std::string response;
|
|
curl_easy_setopt(_h.get(), CURLOPT_WRITEDATA, &response);
|
|
|
|
auto success = curl_easy_perform(_h.get());
|
|
if (success != CURLE_OK) throw std::runtime_error("could not post data");
|
|
return response;
|
|
}
|