Merge pull request #8124 from lioncash/http

Common/HttpRequest: Minor changes and simplifications
This commit is contained in:
Léo Lam 2019-05-27 18:59:23 +02:00 committed by GitHub
commit e3be168328
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 21 deletions

View File

@ -39,17 +39,13 @@ public:
std::string EscapeComponent(const std::string& string); std::string EscapeComponent(const std::string& string);
private: private:
static std::mutex s_curl_was_inited_mutex; static inline std::once_flag s_curl_was_initialized;
static bool s_curl_was_inited;
ProgressCallback m_callback; ProgressCallback m_callback;
std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> m_curl{nullptr, curl_easy_cleanup}; std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> m_curl{nullptr, curl_easy_cleanup};
}; };
std::mutex HttpRequest::Impl::s_curl_was_inited_mutex;
bool HttpRequest::Impl::s_curl_was_inited = false;
HttpRequest::HttpRequest(std::chrono::milliseconds timeout_ms, ProgressCallback callback) HttpRequest::HttpRequest(std::chrono::milliseconds timeout_ms, ProgressCallback callback)
: m_impl(std::make_unique<Impl>(timeout_ms, callback)) : m_impl(std::make_unique<Impl>(timeout_ms, std::move(callback)))
{ {
} }
@ -107,16 +103,9 @@ int HttpRequest::Impl::CurlProgressCallback(Impl* impl, double dlnow, double dlt
} }
HttpRequest::Impl::Impl(std::chrono::milliseconds timeout_ms, ProgressCallback callback) HttpRequest::Impl::Impl(std::chrono::milliseconds timeout_ms, ProgressCallback callback)
: m_callback(callback) : m_callback(std::move(callback))
{ {
{ std::call_once(s_curl_was_initialized, [] { curl_global_init(CURL_GLOBAL_DEFAULT); });
std::lock_guard<std::mutex> lk(s_curl_was_inited_mutex);
if (!s_curl_was_inited)
{
curl_global_init(CURL_GLOBAL_DEFAULT);
s_curl_was_inited = true;
}
}
m_curl.reset(curl_easy_init()); m_curl.reset(curl_easy_init());
if (!m_curl) if (!m_curl)
@ -197,14 +186,14 @@ HttpRequest::Response HttpRequest::Impl::Fetch(const std::string& url, Method me
curl_slist* list = nullptr; curl_slist* list = nullptr;
Common::ScopeGuard list_guard{[&list] { curl_slist_free_all(list); }}; Common::ScopeGuard list_guard{[&list] { curl_slist_free_all(list); }};
for (const std::pair<std::string, std::optional<std::string>>& header : headers) for (const auto& [name, value] : headers)
{ {
if (!header.second) if (!value)
list = curl_slist_append(list, (header.first + ":").c_str()); list = curl_slist_append(list, (name + ':').c_str());
else if (header.second->empty()) else if (value->empty())
list = curl_slist_append(list, (header.first + ";").c_str()); list = curl_slist_append(list, (name + ';').c_str());
else else
list = curl_slist_append(list, (header.first + ": " + *header.second).c_str()); list = curl_slist_append(list, (name + ": " + *value).c_str());
} }
curl_easy_setopt(m_curl.get(), CURLOPT_HTTPHEADER, list); curl_easy_setopt(m_curl.get(), CURLOPT_HTTPHEADER, list);