An HTTP client that checks its assumptions.
Fetch a server health response with timeouts, status checks, and typed JSON.
Download this project ↓01 The shape of the build
An HTTP request can succeed at the transport layer and still return an error status or unexpected data. Reuse a reqwest Client, set a deadline, reject non-success statuses, bound the response body, and deserialize into a typed response. Clap makes the target URL explicit. The default URL points to the signal-server recipe so the complete round trip can be tested locally. This is a client-side tool; do not expose arbitrary URL fetching as a public server endpoint without a separate outbound-network policy.
- 1
Start signal-server on port 3000 in a separate terminal.
- 2
Create a reusable client with a five-second request timeout.
- 3
Check the response status before reading and decoding the bounded body.
- 4
Validate the status field instead of assuming every decoded object is healthy.
02 Get it running
Install Rust stable and extract this project’s ZIP. Run these commands from the extracted http-client folder. The full workbench keeps it under cookbook/http-client.
cargo run -- --url http://127.0.0.1:3000/health
# Start the signal-server recipe first.A healthy service prints signal-server: ok. A non-2xx status, malformed body, oversized response, or non-ok status causes a nonzero exit.
First builds download dependencies. The included Cargo.lock files record the versions resolved during authoring. Use --locked with Cargo commands when you want to enforce those resolutions.
03 The complete source
Every source file below is also in the download. Start with the manifest, then follow the Rust entry point and any UI or test files.
Cargo.toml13 lines +
[package]
name = "http-client"
version = "0.1.0"
edition = "2024"
[dependencies]
clap = { version = "4", features = ["derive"] }
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[workspace]src/main.rs34 lines +
use clap::Parser;
use serde::Deserialize;
use std::time::Duration;
#[derive(Parser)]
struct Args {
#[arg(long, default_value = "http://127.0.0.1:3000/health")]
url: String,
}
#[derive(Deserialize)]
struct Health {
status: String,
service: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.build()?;
let mut response = client.get(&args.url).send().await?.error_for_status()?;
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await? {
if body.len() + chunk.len() > 16 * 1024 {
return Err("health response exceeds 16 KiB".into());
}
body.extend_from_slice(&chunk);
}
let health: Health = serde_json::from_slice(&body)?;
if health.status != "ok" {
return Err("service is not healthy".into());
}
println!("{}: {}", health.service, health.status);
Ok(())
}04 Check the behavior
- □The local signal-server response parses successfully.
- □A 404 URL returns a failure rather than an invented healthy result.
- □--help describes the URL option and default.
05 Know what you are building on
The response is limited to 16 KiB and the request has a five-second timeout.
The target is user-supplied CLI input; this is not a server-side fetch proxy.
There are no automatic retries because retry safety depends on the operation.
Choose one boundary to improve. Write down the new behavior, add a test that demonstrates it, then change the implementation. Keep the original working path intact.