initialize the CURL callbacks only once in the open() function v_0
authorFrantišek Kučera <franta-hg@frantovo.cz>
Tue, 15 Mar 2022 23:29:36 +0100
branchv_0
changeset 10 479557122717
parent 9 9fdbfbe24161
child 11 6b913e82f52a
initialize the CURL callbacks only once in the open() function
src/HTTPClient.cpp
--- a/src/HTTPClient.cpp	Tue Mar 15 23:22:00 2022 +0100
+++ b/src/HTTPClient.cpp	Tue Mar 15 23:29:36 2022 +0100
@@ -89,7 +89,27 @@
 };
 
 HTTPClient* HTTPClient::open() {
-	return new HTTPClient(new HTTPClient::HTTPClientImpl(curl_easy_init()));
+	HTTPClient::HTTPClientImpl* impl = new HTTPClient::HTTPClientImpl(curl_easy_init());
+
+	typedef size_t(*CurlWriteCallback)(char*, size_t, size_t, HTTPClient::HTTPClientImpl*);
+
+	// set response body callback
+	curl_easy_setopt(impl->curl, CURLOPT_WRITEDATA, impl);
+	curl_easy_setopt(impl->curl, CURLOPT_WRITEFUNCTION, (CurlWriteCallback)[](char* buffer, size_t size, size_t nmemb, HTTPClient::HTTPClientImpl * impl)->size_t {
+		size_t r = size * nmemb;
+		impl->responseBody.write(buffer, r);
+		return r;
+	});
+
+	// set response headers callback
+	curl_easy_setopt(impl->curl, CURLOPT_HEADERDATA, impl);
+	curl_easy_setopt(impl->curl, CURLOPT_HEADERFUNCTION, (CurlWriteCallback)[](char* buffer, size_t size, size_t nmemb, HTTPClient::HTTPClientImpl * impl)->size_t {
+		size_t r = size * nmemb;
+		impl->responseHeaders.write(buffer, r);
+		return r;
+	});
+
+	return new HTTPClient(impl);
 }
 
 HTTPClient::~HTTPClient() {
@@ -110,24 +130,6 @@
 	for (size_t i = 0; i < request.headers.size(); i += 2) requestHeders.append(request.headers[i] + ": " + request.headers[i + 1]); // TODO: validate, no CR/LF...
 	curl_easy_setopt(impl->curl, CURLOPT_HTTPHEADER, requestHeders.getList());
 
-	typedef size_t(*CurlWriteCallback)(char*, size_t, size_t, HTTPClient::HTTPClientImpl*);
-
-	// set response body callback
-	curl_easy_setopt(impl->curl, CURLOPT_WRITEDATA, impl);
-	curl_easy_setopt(impl->curl, CURLOPT_WRITEFUNCTION, (CurlWriteCallback)[](char* buffer, size_t size, size_t nmemb, HTTPClient::HTTPClientImpl * impl)->size_t {
-		size_t r = size * nmemb;
-		impl->responseBody.write(buffer, r);
-		return r;
-	});
-
-	// set response headers callback
-	curl_easy_setopt(impl->curl, CURLOPT_HEADERDATA, impl);
-	curl_easy_setopt(impl->curl, CURLOPT_HEADERFUNCTION, (CurlWriteCallback)[](char* buffer, size_t size, size_t nmemb, HTTPClient::HTTPClientImpl * impl)->size_t {
-		size_t r = size * nmemb;
-		impl->responseHeaders.write(buffer, r);
-		return r;
-	});
-
 	// do HTTP call
 	CURLcode result = curl_easy_perform(impl->curl);