Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

HTTP & services

Make an HTTP request and check the response

C++

C++23 has no standard HTTP client. This explicitly uses cpp-httplib with OpenSSL support for HTTPS; check both transport success and HTTP status.

Fragment

Install cpp-httplib and OpenSSL; compile with CPPHTTPLIB_OPENSSL_SUPPORT defined before including httplib.h, and link the required TLS libraries. Include <iostream>/<stdexcept>. These are phase timeouts, not a complete application deadline. The body is retained in memory.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <httplib.h>
#include <iostream>
#include <stdexcept>

httplib::SSLClient client("example.com");
client.set_connection_timeout(3);
client.set_read_timeout(5);
auto response = client.Get("/");
if (!response || response->status < 200 || response->status >= 300) {
    throw std::runtime_error("HTTP request failed");
}
std::cout << response->body;

Send a JSON request body

C++

cpp-httplib can send a serialized JSON string with its content type. This example targets a local plain-HTTP service.

Fragment

Requires cpp-httplib (httplib.h) and <stdexcept>. A separate application must implement POST /items; use a JSON codec when building dynamic JSON.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <httplib.h>
#include <stdexcept>

httplib::Client client("http://127.0.0.1:3000");
client.set_read_timeout(5);
auto response = client.Post("/items",
    R"({"name":"Ada"})", "application/json");
if (!response || response->status >= 400) {
    throw std::runtime_error("POST failed");
}

A complete small HTTP health endpoint

C++

The optional cpp-httplib library provides a blocking HTTP server. This complete example handles one path and checks whether listening succeeds.

Complete program

Install cpp-httplib and expose httplib.h to your compiler. Use the library’s documented thread/linking setup. Visit http://127.0.0.1:3000/health. This is HTTP on loopback; HTTPS requires the library’s TLS configuration.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <httplib.h>
#include <iostream>

int main() {
    httplib::Server server;
    server.Get("/health", [](const httplib::Request&, httplib::Response& response) {
        response.set_content("ok\n", "text/plain");
    });
    if (!server.listen("127.0.0.1", 3000)) {
        std::cerr << "Could not start server\n";
        return 1;
    }
}

Set timeouts and cancel HTTP requests: AbortSignal.timeout, http.Client.Timeout, reqwest, cpp-httplib

C++

The C++ standard library has no networking or HTTP, so timeouts are set on the client library. In cpp-httplib, set_connection_timeout bounds the handshake, set_read_timeout and set_write_timeout bound each socket operation, and set_max_timeout is a total deadline for the request. A failed call returns a Result that converts to false; result.error() says why (here Error::Read), and there is no status to check.

Complete program

Complete program. Starts a local cpp-httplib server on a free port, so it runs offline, and exits.

Before you use this

Not in the standard library: cpp-httplib (header-only) from vcpkg, Conan or a vendored httplib.h.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <httplib.h>

#include <cassert>
#include <chrono>
#include <print>
#include <thread>

using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
    // A local server: /fast answers at once, /slow takes 1 second.
    httplib::Server server;
    server.Get("/fast", [](const httplib::Request&, httplib::Response& res) {
        res.set_content("ok", "text/plain");
    });
    server.Get("/slow", [](const httplib::Request&, httplib::Response& res) {
        std::this_thread::sleep_for(1s);
        res.set_content("late", "text/plain");
    });
    int port = server.bind_to_any_port("127.0.0.1");
    std::thread serving([&] { server.listen_after_bind(); });
    server.wait_until_ready();

    httplib::Client client("127.0.0.1", port);
    client.set_connection_timeout(2s); // the TCP (and TLS) handshake
    client.set_read_timeout(5s);       // each socket read, not the whole response
    client.set_max_timeout(200ms);     // a total deadline for the request

    auto fast = client.Get("/fast");
    assert(fast && fast->status == 200 && fast->body == "ok");

    auto begin = steady_clock::now();
    auto slow = client.Get("/slow");
    auto waited = duration_cast<milliseconds>(steady_clock::now() - begin);
    assert(!slow && waited < 1s); // no response: check result.error(), not the status
    std::println("slow request failed after {}: {}", waited, httplib::to_string(slow.error()));

    server.stop(); // closes the listening socket and returns at once
    serving.join(); // listen returns after the /slow handler finishes
}

In practice: set a connection timeout and a total deadline on every client. With libcurl the same pair is CURLOPT_CONNECTTIMEOUT_MS and CURLOPT_TIMEOUT_MS. For an overall deadline around other work, the standard gives you std::future::wait_for plus a std::stop_token to ask the work to stop.

Built against cpp-httplib 0.65.0. Its client connection and read timeouts default to 300 seconds each, and there is no total deadline unless you call set_max_timeout.

libcurl 8.23.0: CURLOPT_TIMEOUT_MS is the total transfer limit; CURLOPT_LOW_SPEED_LIMIT and CURLOPT_LOW_SPEED_TIME catch a stalled transfer.

std::future::wait_for only stops the waiting: the work keeps running until it checks a std::stop_token. A future from std::async also blocks in its destructor until the task ends.

Serve a small JSON API with routes and path parameters: node:http, ServeMux patterns, axum, cpp-httplib

C++

The standard library has no sockets or HTTP, so the server comes from a library; cpp-httplib is the quickest start. server.Get("/items/:id", handler) registers a route, and the handler reads the :id segment from req.path_params, then sets res.status and res.set_content(body, "application/json"). Handlers run on a thread pool, so shared data needs a mutex. Convert parameters with std::from_chars and check that it consumed the whole segment.

Complete program

Complete program. Serves on a free local port, calls itself with httplib::Client and exits.

Before you use this

Not in the standard library: cpp-httplib (header-only) from vcpkg, Conan or a vendored httplib.h. HTTPS also needs OpenSSL.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <httplib.h>

#include <cassert>
#include <charconv>
#include <format>
#include <map>
#include <mutex>
#include <print>
#include <string>
#include <thread>

int main() {
    std::map<int, std::string> items{{1, "kettle"}, {2, "mug"}};
    std::mutex mutex; // handlers run on a thread pool

    httplib::Server server;
    // ":id" segments are captured in req.path_params.
    server.Get("/items/:id", [&](const httplib::Request& req, httplib::Response& res) {
        const std::string& text = req.path_params.at("id");
        int id = 0;
        auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), id);
        std::lock_guard lock(mutex);
        auto found = items.find(id);
        if (error != std::errc{} || end != text.data() + text.size()) {
            res.status = 400;
            res.set_content(R"({"error":"id must be a number"})", "application/json");
        } else if (found == items.end()) {
            res.status = 404;
            res.set_content(R"({"error":"not found"})", "application/json");
        } else {
            // Real code builds JSON with a library such as nlohmann/json, which also escapes.
            res.set_content(std::format(R"({{"id":{},"name":"{}"}})", id, found->second),
                            "application/json");
        }
    });

    int port = server.bind_to_any_port("127.0.0.1");
    std::thread serving([&] { server.listen_after_bind(); });
    server.wait_until_ready();

    httplib::Client client("127.0.0.1", port);
    auto ok = client.Get("/items/2");
    assert(ok && ok->status == 200 && ok->body == R"({"id":2,"name":"mug"})");
    assert(client.Get("/items/99")->status == 404);
    assert(client.Get("/items/abc")->status == 400);
    // cpp-httplib answers 404, not 405, for a method that has no handler on the path.
    assert(client.Delete("/items/2")->status == 404);
    std::println("GET /items/2 -> {} {}", ok->status, ok->body);

    server.stop();
    serving.join();
}

In practice: build JSON with nlohmann/json, which also escapes strings, rather than std::format. Boost.Beast and Drogon suit larger services. cpp-httplib answers 404, not 405, for a method with no handler on a path; register that method yourself if clients need 405 and an Allow header.

Built against cpp-httplib 0.65.0. HTTPS needs OpenSSL and CPPHTTPLIB_OPENSSL_SUPPORT defined before the include.

bind_to_any_port picks a free port, listen_after_bind blocks serving until stop() is called, and wait_until_ready avoids racing the first request.

std::from_chars does not skip whitespace or accept a leading +, and reports out-of-range values with std::errc::result_out_of_range.

Stop a server cleanly: server.close, http.Server.Shutdown, with_graceful_shutdown, server.stop

C++

Standard C++ can install a handler with std::signal, but the handler may only touch lock-free atomics (or volatile std::sig_atomic_t), so it sets a flag and the main thread does the rest. The server itself comes from a library: in cpp-httplib, server.stop() closes the listening socket, and listen() returns only after the worker pool has finished the requests already running. Join the serving thread and the drain is done.

Complete program

Complete program. Raises SIGTERM itself while a request is running and exits when drained.

Before you use this

Not in the standard library: cpp-httplib (header-only) from vcpkg, Conan or a vendored httplib.h.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <httplib.h>

#include <atomic>
#include <cassert>
#include <chrono>
#include <csignal>
#include <future>
#include <print>
#include <string>
#include <thread>

using namespace std::chrono_literals;

// A signal handler may only do async-signal-safe work: set a lock-free atomic flag.
std::atomic<bool> shutdown_requested{false};
static_assert(std::atomic<bool>::is_always_lock_free);
extern "C" void on_signal(int) { shutdown_requested.store(true); }

int main() {
    std::signal(SIGTERM, on_signal);
    std::signal(SIGINT, on_signal);

    httplib::Server server;
    server.Get("/", [](const httplib::Request&, httplib::Response& res) {
        std::this_thread::sleep_for(300ms); // still running when the signal arrives
        res.set_content("finished", "text/plain");
    });
    int port = server.bind_to_any_port("127.0.0.1");
    std::thread serving([&] { server.listen_after_bind(); });
    server.wait_until_ready();

    // A client request that is in flight during shutdown.
    auto reply = std::async(std::launch::async, [port] {
        auto result = httplib::Client("127.0.0.1", port).Get("/");
        return result ? result->body : httplib::to_string(result.error());
    });
    std::this_thread::sleep_for(50ms);
    std::raise(SIGTERM); // the demo signals itself, as a process manager would

    while (!shutdown_requested.load()) std::this_thread::sleep_for(10ms); // main loop
    std::println("SIGTERM received: draining");
    server.stop();  // closes the listening socket; listen returns once running requests finish
    serving.join();
    assert(reply.get() == "finished"); // the in-flight request was not cut off
    std::println("clean exit");
}

In practice: wait for the flag on the main thread, call stop(), join, then close databases and other resources. On POSIX, a dedicated thread that blocks the signals and calls sigwait avoids the polling loop shown here; Boost.Asio has signal_set for the same job.

Built against cpp-httplib 0.65.0. stop() has no drain deadline: a handler that never returns keeps listen() from returning, so give handlers their own timeouts.

Calling std::println, malloc or locking a mutex inside a signal handler is undefined behavior; set a flag and return.

std::signal's behavior with threads is implementation-defined; on POSIX prefer sigaction, or block the signals and sigwait in one thread.

Build URLs and query strings safely: URLSearchParams, url.Values, the url crate, Boost.URL

C++

The standard library has no URL type or encoder; Boost.URL is the common library. A boost::urls::url built from a fixed base grows with url.segments().push_back(text), which encodes the segment (a / becomes %2F), and url.params().append({key, value}), which encodes the pair with + for spaces. url.params().find(key) and parse_uri read a URL back and decode it.

Complete program

Complete program. Save the file as UTF-8 so "Zürich" is two bytes for ü.

Before you use this

Not in the standard library: Boost.URL (Boost 1.81+) from vcpkg, Conan or your system package manager; link boost_url.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <boost/url.hpp>

#include <cassert>
#include <print>
#include <string>
#include <string_view>

namespace urls = boost::urls;

int main() {
    std::string_view term = "rock & roll", user_name = "ann/marie";

    // Start from a fixed base; segments() and params() encode what you add.
    urls::url url("https://api.example.com/v1");
    url.segments().push_back("users");
    url.segments().push_back(user_name); // '/' inside a segment becomes %2F
    url.segments().push_back("search");
    url.params().append({"q", term});
    url.params().append({"tag", "a+b"}); // repeated key
    url.params().append({"tag", "c d"});
    url.params().append({"city", "Zürich"});

    assert(url.buffer() == "https://api.example.com/v1/users/ann%2Fmarie/search"
                           "?q=rock+%26+roll&tag=a%2Bb&tag=c+d&city=Z%C3%BCrich");

    // Reading decodes again.
    auto q = url.params().find("q");
    assert(q != url.params().end() && (*q).value == term);

    // Pasting raw text in fails to parse (a space) or changes the meaning ('&').
    assert(!urls::parse_uri("https://api.example.com/search?q=rock & roll"));
    assert(urls::parse_uri("https://api.example.com/search?q=R&B")->params().size() == 2);
    std::println("{}", std::string_view(url.buffer()));
}

In practice: never splice user text into a URL string; a space makes it unparseable and an & adds a parameter. HTTP clients usually take parameters separately and encode them, for example cpp-httplib's Client::Get(path, httplib::Params{...}, headers).

Built against Boost 1.92.0 (-lboost_url). Boost.URL follows RFC 3986; ada (the WHATWG parser used by Node.js) matches browser behavior instead.

params() encodes a space as +, like a form; encoded_params() and the encoding_opts overloads give you control over that.

A hand-written encoder keeps the unreserved bytes (A-Z a-z 0-9 - . _ ~) and writes every other byte as %XX with std::format("%{:02X}", c); iterate as unsigned char so bytes above 0x7F are not negative.