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);
}
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());
// 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

View File

@ -13,7 +13,7 @@ namespace cpputils {
~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:
void *curl;

View File

@ -12,7 +12,8 @@ namespace cpputils {
_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);
if (found == _sites.end()) {
return none;

View File

@ -13,7 +13,7 @@ namespace cpputils {
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:
std::map<std::string, std::string> _sites;

View File

@ -9,7 +9,7 @@ namespace cpputils {
public:
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;
};
};