typestar

Reusing a client in Rust

One Client, configured once: connection pooling, timeouts, default headers.

use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(10))
        .user_agent("typestar-cli/2.1")
        .build()?;

    for path in ["healthz", "api/paths?lang=rust"] {
        let url = format!("https://typestar.io/{path}");
        let status = client.get(&url).send().await?.status();
        println!("{status} {path}");
    }
    Ok(())
}

How it works

  1. Building a client per request throws away the pool.
  2. timeout bounds the whole request.
  3. Default headers apply to everything the client sends.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
410
Tokens
124
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 5 of 5 in Requests with reqwest, step 11 of 12 in CLI tools & HTTP clients.

← Previous Next →