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

Rust

reqwest is an optional HTTP library. The blocking client fits a small synchronous CLI; error_for_status handles HTTP 4xx/5xx.

Fragment

Enable reqwest’s blocking feature and appropriate TLS support. Use its async client with a runtime in an async app; text reads the complete body.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let client = reqwest::blocking::Client::builder()
    .timeout(std::time::Duration::from_secs(5)).build()?;
let text = client.get("https://example.com/")
    .send()?.error_for_status()?.text()?;

Send a JSON request body

Rust

The JSON feature serializes a Serde-compatible value and supplies the JSON media type.

Fragment

Requires reqwest with json, serde_json and an active compatible async runtime. client is a configured async reqwest::Client. The target must implement this endpoint.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let response = client.post("http://127.0.0.1:3000/items")
    .json(&serde_json::json!({"name": "Ada"}))
    .send().await?.error_for_status()?;

A complete small HTTP health endpoint

Rust

Axum is an optional web framework running on Tokio. This complete program serves one route on loopback.

Complete program

Cargo dependencies: axum = "0.8"; tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }. Save as src/main.rs. Visit http://127.0.0.1:3000/health.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use axum::{routing::get, Router};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new().route("/health", get(|| async { "ok\n" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app).await?;
    Ok(())
}

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

Rust

The standard library has no HTTP client, so timeouts come from reqwest, the usual client. ClientBuilder::timeout sets a total deadline for each request (connecting, headers and the whole body), connect_timeout bounds only the handshake, and RequestBuilder::timeout overrides the total for one call. A timed-out call returns a reqwest::Error whose is_timeout() is true. By default a reqwest client has no total timeout.

Complete program

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

Before you use this

Not in the standard library: cargo add tokio --features full && cargo add reqwest axum

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::time::Duration;

use axum::{Router, routing::get};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A local server: /fast answers at once, /slow takes 5 seconds.
    let app = Router::new().route("/fast", get(|| async { "ok" })).route(
        "/slow",
        get(|| async {
            tokio::time::sleep(Duration::from_secs(5)).await;
            "late"
        }),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
    let base = format!("http://{}", listener.local_addr()?);
    tokio::spawn(async move { axum::serve(listener, app).await });

    // timeout is a total deadline: connecting, headers and the whole body.
    // connect_timeout bounds only the TCP (and TLS) handshake.
    let client = reqwest::Client::builder()
        .timeout(Duration::from_millis(200))
        .connect_timeout(Duration::from_secs(2))
        .build()?;

    let body = client.get(format!("{base}/fast")).send().await?.text().await?;
    assert_eq!(body, "ok");

    let err = client.get(format!("{base}/slow")).send().await.unwrap_err();
    assert!(err.is_timeout());
    println!("slow request: is_timeout = {}", err.is_timeout());

    // A tighter limit for one request overrides the client's.
    let short = client
        .get(format!("{base}/slow"))
        .timeout(Duration::from_millis(50))
        .send()
        .await;
    assert!(short.unwrap_err().is_timeout());

    // tokio::time::timeout bounds any future, such as several calls in a row.
    let both = tokio::time::timeout(Duration::from_millis(100), async {
        client.get(format!("{base}/fast")).send().await?;
        client.get(format!("{base}/slow")).send().await
    })
    .await;
    assert!(both.is_err()); // Elapsed: the outer deadline fired first
    Ok(())
}

In practice: build one Client with both limits at startup and reuse it (it pools connections). For a deadline that spans several calls, or any other future, wrap it in tokio::time::timeout, which returns Err(Elapsed) and drops the work.

Built with reqwest 0.13.5, axum 0.8.9 and tokio 1.54.1. The blocking client (feature "blocking") has the same timeout and connect_timeout methods, with a 30-second default timeout.

Dropping a future cancels it: when tokio::time::timeout fires, the request in flight is abandoned and its connection closed.

std only: TcpStream::connect_timeout bounds the handshake and set_read_timeout / set_write_timeout bound each read or write call (a timed-out read is WouldBlock on Unix, TimedOut on Windows). These are not a total deadline: a server sending one byte per second never trips them.

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

Rust

The standard library has no HTTP server; axum on the tokio runtime is the usual choice. Router::new().route("/items/{id}", get(get_item)) declares a route, and each handler takes typed extractors that parse the request for it: Path<u32> for the {id} segment, State<Db> for shared data and Json<T> for a body that serde deserializes. A handler returns anything that converts into a response, such as Json<Item>, a (StatusCode, Json<T>) pair or Result<Json<T>, StatusCode>.

Complete program

Complete program. Serves on a free local port, calls itself with reqwest and exits.

Before you use this

Not in the standard library: cargo add tokio --features full && cargo add serde --features derive && cargo add axum serde_json && cargo add reqwest --features json

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::{Json, Router, routing::get};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Item {
    id: u32,
    name: String,
}

#[derive(Deserialize)]
struct NewItem {
    name: String,
}

type Db = Arc<Mutex<HashMap<u32, Item>>>;

// Extractors parse the request: Path<u32> answers 400 for /items/abc, Json<T> rejects a bad body.
async fn get_item(Path(id): Path<u32>, State(db): State<Db>) -> Result<Json<Item>, StatusCode> {
    let item = db.lock().unwrap().get(&id).cloned();
    item.map(Json).ok_or(StatusCode::NOT_FOUND)
}

async fn create_item(State(db): State<Db>, Json(input): Json<NewItem>) -> (StatusCode, Json<Item>) {
    let mut db = db.lock().unwrap();
    let item = Item { id: db.len() as u32 + 1, name: input.name };
    db.insert(item.id, item.clone());
    (StatusCode::CREATED, Json(item))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let kettle = Item { id: 1, name: "kettle".into() };
    let db: Db = Arc::new(Mutex::new(HashMap::from([(1, kettle)])));
    // axum 0.8 path syntax: {id}. A known path with the wrong method gets 405 automatically.
    let app = Router::new()
        .route("/items", axum::routing::post(create_item))
        .route("/items/{id}", get(get_item))
        .with_state(db);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
    let base = format!("http://{}", listener.local_addr()?);
    tokio::spawn(async move { axum::serve(listener, app).await });

    let client = reqwest::Client::new();
    let created = client
        .post(format!("{base}/items"))
        .json(&serde_json::json!({ "name": "mug" }))
        .send()
        .await?;
    assert_eq!(created.status(), StatusCode::CREATED);
    let item: Item = created.json().await?;

    let fetched: Item = client.get(format!("{base}/items/{}", item.id)).send().await?.json().await?;
    assert_eq!(fetched, item);
    let status = |path: &str| client.get(format!("{base}{path}")).send();
    assert_eq!(status("/items/99").await?.status(), StatusCode::NOT_FOUND);
    assert_eq!(status("/items/abc").await?.status(), StatusCode::BAD_REQUEST);
    let delete = client.delete(format!("{base}/items/1")).send().await?;
    assert_eq!(delete.status(), StatusCode::METHOD_NOT_ALLOWED);
    println!("GET /items/2 -> {fetched:?}; DELETE -> {}", delete.status());
    Ok(())
}

In practice: let the extractors reject bad input (a non-numeric id is 400, a malformed JSON body 400, a missing Content-Type 415), and keep shared state behind Arc<Mutex<…>> or a database pool. A path registered for another method answers 405 with an Allow header by itself.

Built with axum 0.8.9, tokio 1.54.1, serde 1.0 and reqwest 0.13.5. axum 0.8 changed path syntax from /:id to /{id}; older tutorials using :id fail to match.

Do not hold a std::sync::Mutex guard across an .await; lock, copy what you need and release, as these handlers do.

Json<T> answers 422 when the JSON is well formed but does not match T (for example a missing name), and 400 when it does not parse.

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

Rust

std has no signal handling and cannot interrupt a blocking accept(), so graceful shutdown comes from the async stack. In axum, axum::serve(listener, app).with_graceful_shutdown(signal) takes a future: when it completes, the server stops accepting, lets in-flight requests finish and closes idle keep-alive connections, and serve returns once all of them are done. tokio::signal::ctrl_c() and tokio::signal::unix::signal(SignalKind::terminate()) are the usual futures, combined with tokio::select!.

Complete program

Complete program (Unix: it sends itself SIGTERM with the kill command) and exits when drained.

Before you use this

Not in the standard library: cargo add tokio --features full && cargo add axum reqwest

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::time::Duration;

use axum::{Router, routing::get};
use tokio::signal::unix::{SignalKind, signal};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new().route(
        "/",
        get(|| async {
            tokio::time::sleep(Duration::from_millis(300)).await; // still running at the signal
            "finished"
        }),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
    let addr = listener.local_addr()?;

    // Resolves on Ctrl-C (SIGINT) or SIGTERM, which process managers and Kubernetes send.
    let mut sigterm = signal(SignalKind::terminate())?;
    let shutdown_signal = async move {
        tokio::select! {
            _ = tokio::signal::ctrl_c() => {}
            _ = sigterm.recv() => {}
        }
        println!("signal received: no new connections, draining");
    };
    // with_graceful_shutdown stops accepting, then waits for in-flight requests.
    let server = tokio::spawn(async move {
        axum::serve(listener, app).with_graceful_shutdown(shutdown_signal).await
    });

    let in_flight = tokio::spawn(reqwest::get(format!("http://{addr}/")));
    tokio::time::sleep(Duration::from_millis(50)).await;
    // For the demo, send ourselves SIGTERM (Unix), as a process manager would.
    std::process::Command::new("kill")
        .args(["-TERM", &std::process::id().to_string()])
        .status()?;

    // Bound the drain so one stuck request cannot block exit.
    tokio::time::timeout(Duration::from_secs(10), server).await???;
    assert_eq!(in_flight.await??.text().await?, "finished");
    assert!(tokio::net::TcpStream::connect(addr).await.is_err()); // listener closed
    println!("in-flight request completed; exiting");
    Ok(())
}

In practice: register the SIGTERM stream at startup, before anything can send it, and bound only the drain: start a deadline when the signal arrives (for example tokio::select! between the server future and tokio::time::sleep(limit) after the signal), so one stuck request cannot block exit. Wrapping the whole server in tokio::time::timeout would stop it that long after startup, signal or not. Close database pools and other resources after serve returns.

Built with axum 0.8.9, tokio 1.54.1 and reqwest 0.13.5. tokio::signal::unix is Unix-only; on Windows use ctrl_c() or tokio::signal::windows.

Without a SIGTERM listener the default action kills the process at once, cutting off in-flight requests.

std-only servers use an AtomicBool that the accept loop checks plus a wake-up connection to unblock accept(); the signal-hook crate sets such a flag from a signal handler.

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

Rust

The standard library has no URL type; the url crate, which follows the WHATWG URL standard like browsers, is the usual one. Url::parse checks a base URL, path_segments_mut() pushes path segments and encodes each one (a / inside becomes %2F), and query_pairs_mut().append_pair(key, value) adds encoded query pairs. query_pairs() decodes them again.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add url

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use url::Url;

fn main() -> Result<(), url::ParseError> {
    let (term, user_name) = ("rock & roll", "ann/marie");

    // Start from a fixed base; each mutator encodes its own part of the URL.
    let mut url = Url::parse("https://api.example.com/v1/")?;
    url.path_segments_mut()
        .expect("an https URL has a path")
        .pop_if_empty() // drop the empty segment after the trailing '/'
        .extend(["users", user_name, "search"]); // a '/' inside a segment becomes %2F
    url.query_pairs_mut()
        .append_pair("q", term)
        .append_pair("tag", "a+b") // repeated key
        .append_pair("tag", "c d")
        .append_pair("city", "Zürich");

    assert_eq!(
        url.as_str(),
        "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.
    let tags: Vec<String> = url
        .query_pairs()
        .filter(|(key, _)| key == "tag")
        .map(|(_, value)| value.into_owned())
        .collect();
    assert_eq!(tags, ["a+b", "c d"]);

    // Formatting user text straight into the URL breaks it: '&' starts a new parameter.
    let broken = Url::parse(&format!("https://api.example.com/search?q={term}"))?;
    assert_eq!(broken.query_pairs().count(), 2);
    println!("{url}");
    Ok(())
}

In practice: start from a fixed base URL and put user text only through these mutators, never through format!. If the base ends in /, call pop_if_empty() before pushing, or the empty last segment leaves a double slash.

Built with url 2.5.8. path_segments_mut() returns Err only for URLs that cannot have a path, such as mailto:; for http and https it always succeeds.

query_pairs_mut uses form encoding, so a space becomes +, as in browsers. For %20 (some signature schemes need it), encode with the percent-encoding crate's utf8_percent_encode and your own AsciiSet.

std only: keep the unreserved bytes (A-Z a-z 0-9 - . _ ~) and write every other byte of the UTF-8 text as %XX, one component at a time.