| 146 | |
| 147 | namespace Http { |
| 148 | Response perform(const Request& req) |
| 149 | { |
| 150 | Response res; |
| 151 | |
| 152 | FILE* upload = nullptr; |
| 153 | long uploadSize = 0; |
| 154 | if (req.uploadPath) { |
| 155 | upload = fopen(req.uploadPath, "rb"); |
| 156 | if (!upload) { |
| 157 | res.result = Result::FileError; |
| 158 | return res; |
| 159 | } |
| 160 | fseek(upload, 0, SEEK_END); |
| 161 | uploadSize = ftell(upload); |
| 162 | rewind(upload); |
| 163 | if (uploadSize < 0) { |
| 164 | fclose(upload); |
| 165 | res.result = Result::FileError; |
| 166 | return res; |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | CURL* curl = curlReady() ? curl_easy_init() : nullptr; |
| 171 | if (!curl) { |
| 172 | if (upload) { |
| 173 | fclose(upload); |
| 174 | } |
| 175 | res.result = Result::Unavailable; |
| 176 | return res; |
| 177 | } |
| 178 | |
| 179 | struct curl_slist* hl = headerSlist(req.headers); |
| 180 | UploadProgress prog; |
| 181 | applyCommonOptions(curl, req, &res.body, req.captureHeaders ? &res.headers : nullptr); |
| 182 | if (req.method && req.method[0]) { |
| 183 | curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, req.method); // GET/POST/PUT/PATCH/DELETE |
| 184 | } |
| 185 | if (hl) { |
| 186 | curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hl); |
| 187 | } |
| 188 | if (upload) { |
| 189 | curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); // streamed request body |
| 190 | curl_easy_setopt(curl, CURLOPT_READDATA, upload); |
| 191 | curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)uploadSize); |
| 192 | curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, uploadProgress); |
| 193 | curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &prog); |
| 194 | } |
| 195 | else { |
| 196 | if (req.body && req.bodySize > 0) { |
| 197 | curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req.body); |
| 198 | curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req.bodySize); |
| 199 | } |
| 200 | curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, abortOnScriptCancel); |
| 201 | } |
| 202 | |
| 203 | const CURLcode code = curl_easy_perform(curl); |
| 204 | if (code == CURLE_OK) { |
| 205 | curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &res.httpStatus); |
no test coverage detected