-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.cpp
More file actions
83 lines (60 loc) · 1.92 KB
/
Copy pathhttp.cpp
File metadata and controls
83 lines (60 loc) · 1.92 KB
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
#include "http.h"
#include "constants.h"
using namespace containery;
size_t writeCallback(char* ptr, size_t size, size_t nmemb, std::string* data) {
data->append(ptr, size * nmemb);
return size * nmemb;
}
// TODO: implement better error handling - 404s etc
HttpResponse makeHttpGetRequest(
const string& url,
vector<std::string> header_lines,
bool is_head_request,
std::string file_output,
bool follow_location
){
CURL* curl = curl_easy_init();
std::string response;
struct curl_slist* headers = nullptr;
if (header_lines.size() > 0){
for (const auto& header_line: header_lines){
headers = curl_slist_append(headers, header_line.c_str());
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
}
if (is_head_request){
curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
}
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
FILE* file = nullptr;
if (file_output == ""){
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
} else {
file = fopen(file_output.c_str(), "wb");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, nullptr);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
}
if (follow_location){
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
}
CURLcode res = curl_easy_perform(curl);
int http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
// cleanup
curl_easy_cleanup(curl);
if (headers != nullptr){
curl_slist_free_all(headers);
}
if (file != nullptr){
fclose(file);
}
json json_response = nullptr;
if (!is_head_request && file_output == ""){
json_response = json::parse(response);
}
return HttpResponse{
.json_response = json_response,
.code = http_code
};
}