brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: curl libcurl turns a working command into C code

Curl
~/tips/tip-curl-libcurl-source

curl --libcurl code.c -s -H 'Accept: application/json' https://example.com/api/items

Get the libcurl options behind a command line, as a starting point for your own code.

When I move a request from the terminal into a program, I want the exact options the command used. --libcurl writes them out as a small C program.

Run the command as usual and add a file name:

curl --libcurl code.c -s -H 'Accept: application/json' https://example.com/api/items

curl does the request, and code.c now holds a main() with one curl_easy_setopt() line per setting, such as CURLOPT_URL, CURLOPT_HTTPHEADER, CURLOPT_USERAGENT and CURLOPT_MAXREDIRS. It also shows defaults the tool sets that you never typed, like the user agent and TCP keepalive.

Even if you do not write C, this is useful. PHP’s curl extension, Python’s pycurl and many other bindings use the same CURLOPT_ names, so the list tells you which settings to copy into your code.

The output is a starting point, not finished code. Callbacks for writing data cannot be generated, so curl lists them in a comment at the end instead. Secrets you passed on the command line, like a token in a header or a -u password, end up in the file as plain text, so do not commit it. Some values also depend on the build you ran it with, such as the TLS version setting.

Further reading: curl man page, libcurl: curl_easy_setopt

More Curl tips curl --trace-ascii – https://example.com/ Retry-After: 120 curl -fsS --fail-early \ url = "https://example.com/data/latest.json" curl -4 -s -o /dev/null -w '%{remote_ip} %{http_code}\n' https://example.com/ All Curl tips (71) All topics

Link