Add timeout to HttpClient

This commit is contained in:
Sebastian Messmer 2015-11-24 08:23:20 +01:00
parent feb806b392
commit 3fe90ea434
5 changed files with 9 additions and 5 deletions

View File

@ -26,7 +26,7 @@ namespace cpputils {
curl_easy_cleanup(curl); curl_easy_cleanup(curl);
} }
optional <string> CurlHttpClient::get(const string &url) { optional <string> CurlHttpClient::get(const string &url, optional<long> timeoutMsec) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
// example.com is redirected, so we tell libcurl to follow redirection // example.com is redirected, so we tell libcurl to follow redirection
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
@ -35,6 +35,9 @@ namespace cpputils {
ostringstream out; ostringstream out;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CurlHttpClient::write_data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CurlHttpClient::write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
if (timeoutMsec != none) {
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, *timeoutMsec);
}
// Perform the request, res will get the return code // Perform the request, res will get the return code
CURLcode res = curl_easy_perform(curl); CURLcode res = curl_easy_perform(curl);
// Check for errors // Check for errors

View File

@ -13,7 +13,7 @@ namespace cpputils {
~CurlHttpClient(); ~CurlHttpClient();
boost::optional <std::string> get(const std::string &url) override; boost::optional <std::string> get(const std::string &url, boost::optional<long> timeoutMsec = boost::none) override;
private: private:
void *curl; void *curl;

View File

@ -12,7 +12,8 @@ namespace cpputils {
_sites[url] = content; _sites[url] = content;
} }
optional<string> FakeHttpClient::get(const string &url) { optional<string> FakeHttpClient::get(const string &url, optional<long> timeoutMsec) {
UNUSED(timeoutMsec);
auto found = _sites.find(url); auto found = _sites.find(url);
if (found == _sites.end()) { if (found == _sites.end()) {
return none; return none;

View File

@ -13,7 +13,7 @@ namespace cpputils {
void addWebsite(const std::string &url, const std::string &content); void addWebsite(const std::string &url, const std::string &content);
boost::optional<std::string> get(const std::string &url) override; boost::optional<std::string> get(const std::string &url, boost::optional<long> timeoutMsec = boost::none) override;
private: private:
std::map<std::string, std::string> _sites; std::map<std::string, std::string> _sites;

View File

@ -9,7 +9,7 @@ namespace cpputils {
public: public:
virtual ~HttpClient() {} virtual ~HttpClient() {}
virtual boost::optional<std::string> get(const std::string& url) = 0; virtual boost::optional<std::string> get(const std::string& url, boost::optional<long> timeoutMsec = boost::none) = 0;
}; };
}; };