-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFetch.cpp
91 lines (72 loc) · 1.44 KB
/
Fetch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
// Copyright (c) 2016 James A. Chappell
//
#include "Fetch.h"
#include <stdexcept>
#include <cstring>
using namespace std;
using namespace Storage_B::Curlpp;
class CurlGlobalInit
{
public:
CurlGlobalInit()
{
Curl::GlobalInit();
}
CurlGlobalInit(const CurlGlobalInit&) = delete;
CurlGlobalInit& operator=(const CurlGlobalInit&) = delete;
~CurlGlobalInit()
{
Curl::GlobalCleanup();
}
};
static CurlGlobalInit init;
Fetch::Fetch(const char *url)
: curl_(make_unique<Curl>())
{
curl_->SetOpt(CURLOPT_WRITEFUNCTION, read_result);
if (url)
{
Url(url);
}
}
long Fetch::fetch(CURLoption option, string& result) const
{
curl_->SetOpt(option, &result);
long http_status;
CURLcode res = curl_->Perform(http_status);
if (res != CURLE_OK)
{
string error;
if (curl_->error() && (strlen(curl_->error()) > 0))
{
error = curl_->error();
}
else
{
error = "CURLcode = " + to_string(res);
}
switch(res)
{
case CURLE_URL_MALFORMAT:
throw logic_error(error);
break;
default:
throw runtime_error(error);
break;
}
}
return http_status;
}
size_t Fetch::read_result(void *buffer, size_t size, size_t nmemb,
void *stream)
{
auto *out = static_cast<string *>(stream);
if (out)
{
auto buf_size = size * nmemb;
*out += string((const char* )buffer);
return buf_size;
}
return -1;
}