diff --git a/premake.make b/premake.make index acf816c..817f530 100644 --- a/premake.make +++ b/premake.make @@ -1,7 +1,7 @@ LDLIBS := -lcurl -lsclogging -lscterm MAJOR := 1 -MINOR := 1 +MINOR := 2 PATCH := 0 GENERATELIBHEADER := 1 diff --git a/src/requester.cpp b/src/requester.cpp index 9218a53..73a6f2a 100644 --- a/src/requester.cpp +++ b/src/requester.cpp @@ -54,18 +54,20 @@ std::string requester::post(const std::string& url, const std::string& json) { curl_easy_setopt(_h.get(), CURLOPT_POST, 1L); curl_easy_setopt(_h.get(), CURLOPT_POSTFIELDS, json.c_str()); curl_easy_setopt(_h.get(), CURLOPT_POSTFIELDSIZE, json.size()); - - struct curl_slist* headers {nullptr}; - headers = curl_slist_append(headers, "Content-Type: application/json"); - std::unique_ptr hdrs {headers, curl_slist_free_all}; - curl_easy_setopt(_h.get(), CURLOPT_HTTPHEADER, headers); - perform(); + add_header("Content-Type: application/json"); + perform_with_headers(); return _text; } +void requester::add_header(const std::string& hdr) { + _headers.push_back(hdr); +} + void requester::perform() { - _text = ""; - curl_easy_setopt(_h.get(), CURLOPT_WRITEDATA, this); + _text = ""; // clear response text + curl_easy_setopt(_h.get(), CURLOPT_WRITEDATA, this); // setup callback user data + + // perform request auto success = curl_easy_perform(_h.get()); if (success != CURLE_OK) { std::ostringstream oss; @@ -74,6 +76,22 @@ void requester::perform() { } } +void requester::perform_with_headers() { + if (_headers.size()) { + // setup headers + struct curl_slist* headers {nullptr}; + for (const auto& hdr : _headers) { + headers = curl_slist_append(headers, hdr.c_str()); + } + curl_easy_setopt(_h.get(), CURLOPT_HTTPHEADER, headers); + std::unique_ptr hdrs {headers, curl_slist_free_all}; + _headers.clear(); // start fresh for next request + perform(); + } else { + perform(); + } +} + void requester::check_status(long status) { auto success = curl_easy_getinfo(_h.get(), CURLINFO_RESPONSE_CODE, &_status); if (success != CURLE_OK || _status != status) { diff --git a/src/requester.hpp b/src/requester.hpp index 440c0ac..aab88fa 100644 --- a/src/requester.hpp +++ b/src/requester.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -31,16 +32,20 @@ namespace sc { // perform a http get request std::string get(const std::string& url); - // perform a http post request + // perform a http post request with a json payload std::string post(const std::string& url, const std::string& json); + void add_header(const std::string& hdr); + private: std::unique_ptr _h {nullptr, curl_easy_cleanup}; sc::logger* _logger {nullptr}; std::string _text; long _status; + std::vector _headers; void perform(); + void perform_with_headers(); void check_status(long status); };