Skip to content

Instantly share code, notes, and snippets.

@rbakbashev
Created December 10, 2014 10:41
Show Gist options
  • Select an option

  • Save rbakbashev/7d7c19ecb2d8b822b642 to your computer and use it in GitHub Desktop.

Select an option

Save rbakbashev/7d7c19ecb2d8b822b642 to your computer and use it in GitHub Desktop.
Simple to use http getter using libcurl
#include "get.hpp"
void Get_init()
{
curl = curl_easy_init();
if (!curl)
throw std::runtime_error("curl_easy_init() failed");
}
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb,
void *userp)
{
size_t realsize = size * nmemb;
GetStruct *mem = (GetStruct*)userp;
delete [] mem->memory;
mem->memory = new char[mem->size + realsize + 1];
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
GetStruct Get(std::string uri)
{
GetStruct chunk;
chunk.memory = new char[1];
chunk.size = 0;
curl_global_init(CURL_GLOBAL_ALL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);
curl_easy_setopt(curl, CURLOPT_URL, uri.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("curl_easy_perform() failed:\n");
throw std::runtime_error(curl_easy_strerror(res));
}
return chunk;
}
void Get_destroy()
{
curl_easy_cleanup(curl);
}
#ifndef GET_HPP
#define GET_HPP
#include <string>
#include <curl/curl.h>
#include <stdexcept>
#include <memory>
#include <cstring>
static CURL *curl;
struct GetStruct {
char *memory;
size_t size;
};
void Get_init();
GetStruct Get(std::string uri);
void Get_destroy();
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment