add AsyncWebRequest::timeout

This commit is contained in:
mat 2024-01-03 23:12:23 -03:00
parent 1ee1352d70
commit 13ac3359f7
2 changed files with 14 additions and 2 deletions

View file

@ -7,7 +7,7 @@
#include "general.hpp"
#include <ghc/fs_fwd.hpp>
#include <mutex>
#include <chrono>
namespace geode::utils::web {
GEODE_DLL void openLinkInBrowser(std::string const& url);
@ -185,6 +185,10 @@ namespace geode::utils::web {
* sets the content type to application/json.
*/
AsyncWebRequest& postFields(matjson::Value const& fields);
/**
* Specify a timeout, in seconds, in which the request will fail.
*/
AsyncWebRequest& timeout(std::chrono::seconds seconds);
/**
* Specify a callback to run if the download fails. The callback is
* always ran in the GD thread, so interacting with UI is safe

View file

@ -204,6 +204,7 @@ public:
bool m_sent = false;
std::variant<std::monostate, std::ostream*, ghc::filesystem::path> m_target;
std::vector<std::string> m_httpHeaders;
std::chrono::seconds m_timeoutSeconds;
SentAsyncWebRequestHandle send(AsyncWebRequest&);
};
@ -241,7 +242,9 @@ SentAsyncWebRequest::Impl::Impl(SentAsyncWebRequest* self, AsyncWebRequest const
if (req.m_impl->m_cancelled) m_cancelleds.push_back(req.m_impl->m_cancelled);
if (req.m_impl->m_expect) m_expects.push_back(req.m_impl->m_expect);
std::thread([this]() {
auto timeoutSeconds = req.m_impl->m_timeoutSeconds;
std::thread([this, timeoutSeconds]() {
AWAIT_RESUME();
auto curl = curl_easy_init();
@ -301,6 +304,11 @@ SentAsyncWebRequest::Impl::Impl(SentAsyncWebRequest* self, AsyncWebRequest const
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, m_postFields.size());
}
// Timeout
if (timeoutSeconds.count()) {
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeoutSeconds.count());
}
// Track progress
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
// Follow redirects