#include "HTTPClient.h" #include "HTTPRequest.h" #include "HTTPResponse.h" #include "lib/io/URL.h" #include "lib/logging/logging.h" #include #include namespace bts::io::http { static size_t write_data_( void *ptr, size_t size, size_t nmemb, std::string *data) { data->append((char *)ptr, size * nmemb); return size * nmemb; } HTTPResponse HTTPClient::get(const HTTPRequest &request) { auto *curl = curl_easy_init(); auto url_str = request.url().to_string(); // LOG(md, bts::Info, "do GET: {}", url_str); curl_easy_setopt(curl, CURLOPT_URL, url_str.c_str()); struct curl_slist *request_headers = NULL; for (const auto &[k, v] : request.headers()) { request_headers = curl_slist_append( request_headers, fmt::format("{}: {}", k, v).c_str()); } std::string response_string; std::string header_string; std::string response_header_string; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string); char *url; long response_code; double elapsed; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed); curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url); // curl_easy_getinfo(curl, CURLINFO_HEADER_OUT, &response_header_string); curl_easy_perform(curl); curl_easy_cleanup(curl); curl = NULL; HTTPResponse response; response.headers() = HTTPHeaders(response_header_string); response.body() = std::move(response_string); response.code() = response_code; // LOG(md, bts::Info, "do GET: {}. Received response:\n{}", url_str, response); return response; } } // namespace bts::io::http