curly/requester.cpp
2020-09-02 11:25:13 +02:00

60 lines
1.5 KiB
C++

//
// requester.cpp
// curly
//
// Created by Bob Polis at 2020-09-01
// Copyright (c) 2020 SwiftCoder. All rights reserved.
//
#include "requester.hpp"
#include <libsclogging.hpp>
#include <vector>
#include <cstring>
#include <stdexcept>
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<char>* dest {reinterpret_cast<std::vector<char>*>(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() {
curl_easy_cleanup(_h);
}
requester::requester(requester&& other) {
_h = other._h;
other._h = nullptr;
}
requester& requester::operator=(requester &&other) {
if (this != &other) {
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<char> 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;
}