examples: improve global init, error checks and returning errors

- add `curl_global_init()` and `curl_global_cleanup()` where missing.
- check the result of `curl_global_init()` where missing.
- return the last curl error from `main()`.
- drop Win32-specific socket initialization in favor of `curl_global_init()`.
- rename some outliers to `res` for curl result code.
- fix cleanup in some error cases.

Inspired by Joshua's report on examples.

Closes #19053
This commit is contained in:
Viktor Szakats 2025-10-13 16:30:18 +02:00
parent 3049c8e0a0
commit 4c7507daf9
No known key found for this signature in database
GPG key ID: B5ABD165E2AEF201
129 changed files with 990 additions and 485 deletions

View file

@ -87,39 +87,42 @@ int main(int argc, const char *argv[])
{
CURL *easy;
struct read_ctx rctx;
CURLcode res;
const char *payload = "Hello, friend!";
CURLcode res = curl_global_init(CURL_GLOBAL_ALL);
if(res)
return (int)res;
memset(&rctx, 0, sizeof(rctx));
easy = curl_easy_init();
if(!easy)
return 1;
if(easy) {
if(argc == 2)
curl_easy_setopt(easy, CURLOPT_URL, argv[1]);
else
curl_easy_setopt(easy, CURLOPT_URL, "wss://example.com");
if(argc == 2)
curl_easy_setopt(easy, CURLOPT_URL, argv[1]);
else
curl_easy_setopt(easy, CURLOPT_URL, "wss://example.com");
curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, writecb);
curl_easy_setopt(easy, CURLOPT_WRITEDATA, easy);
curl_easy_setopt(easy, CURLOPT_READFUNCTION, readcb);
/* tell curl that we want to send the payload */
rctx.easy = easy;
rctx.blen = strlen(payload);
memcpy(rctx.buf, payload, rctx.blen);
curl_easy_setopt(easy, CURLOPT_READDATA, &rctx);
curl_easy_setopt(easy, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, writecb);
curl_easy_setopt(easy, CURLOPT_WRITEDATA, easy);
curl_easy_setopt(easy, CURLOPT_READFUNCTION, readcb);
/* tell curl that we want to send the payload */
rctx.easy = easy;
rctx.blen = strlen(payload);
memcpy(rctx.buf, payload, rctx.blen);
curl_easy_setopt(easy, CURLOPT_READDATA, &rctx);
curl_easy_setopt(easy, CURLOPT_UPLOAD, 1L);
/* Perform the request, res gets the return code */
res = curl_easy_perform(easy);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* Perform the request, res gets the return code */
res = curl_easy_perform(easy);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(easy);
return 0;
/* always cleanup */
curl_easy_cleanup(easy);
}
curl_global_cleanup();
return (int)res;
}