From 3fe90ea434f9f202276fbd196c04a78da6908b81 Mon Sep 17 00:00:00 2001 From: Sebastian Messmer Date: Tue, 24 Nov 2015 08:23:20 +0100 Subject: [PATCH] Add timeout to HttpClient --- network/CurlHttpClient.cpp | 5 ++++- network/CurlHttpClient.h | 2 +- network/FakeHttpClient.cpp | 3 ++- network/FakeHttpClient.h | 2 +- network/HttpClient.h | 2 +- 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/network/CurlHttpClient.cpp b/network/CurlHttpClient.cpp index ad846f23..c80a0a62 100644 --- a/network/CurlHttpClient.cpp +++ b/network/CurlHttpClient.cpp @@ -26,7 +26,7 @@ namespace cpputils { curl_easy_cleanup(curl); } - optional CurlHttpClient::get(const string &url) { + optional CurlHttpClient::get(const string &url, optional timeoutMsec) { curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // example.com is redirected, so we tell libcurl to follow redirection curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); @@ -35,6 +35,9 @@ namespace cpputils { ostringstream out; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CurlHttpClient::write_data); 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 CURLcode res = curl_easy_perform(curl); // Check for errors diff --git a/network/CurlHttpClient.h b/network/CurlHttpClient.h index 50f3e72d..d86831b7 100644 --- a/network/CurlHttpClient.h +++ b/network/CurlHttpClient.h @@ -13,7 +13,7 @@ namespace cpputils { ~CurlHttpClient(); - boost::optional get(const std::string &url) override; + boost::optional get(const std::string &url, boost::optional timeoutMsec = boost::none) override; private: void *curl; diff --git a/network/FakeHttpClient.cpp b/network/FakeHttpClient.cpp index fb81f82b..098ffa3d 100644 --- a/network/FakeHttpClient.cpp +++ b/network/FakeHttpClient.cpp @@ -12,7 +12,8 @@ namespace cpputils { _sites[url] = content; } - optional FakeHttpClient::get(const string &url) { + optional FakeHttpClient::get(const string &url, optional timeoutMsec) { + UNUSED(timeoutMsec); auto found = _sites.find(url); if (found == _sites.end()) { return none; diff --git a/network/FakeHttpClient.h b/network/FakeHttpClient.h index 5fd9e698..eb63d956 100644 --- a/network/FakeHttpClient.h +++ b/network/FakeHttpClient.h @@ -13,7 +13,7 @@ namespace cpputils { void addWebsite(const std::string &url, const std::string &content); - boost::optional get(const std::string &url) override; + boost::optional get(const std::string &url, boost::optional timeoutMsec = boost::none) override; private: std::map _sites; diff --git a/network/HttpClient.h b/network/HttpClient.h index 8578f0d5..6fc3b82b 100644 --- a/network/HttpClient.h +++ b/network/HttpClient.h @@ -9,7 +9,7 @@ namespace cpputils { public: virtual ~HttpClient() {} - virtual boost::optional get(const std::string& url) = 0; + virtual boost::optional get(const std::string& url, boost::optional timeoutMsec = boost::none) = 0; }; };