Skip to main content
Be Bitwise
RustCapstone: CLI Network Tool

The Complete Tool

Time to bolt the pieces together into a CLI you can actually run.

The run Function

rust
// Returns whether every check passed; main turns that into an exit code.
fn run(args: Args) -> Result<bool, Box<dyn std::error::Error>> {
println!("Checking {} URLs (timeout: {}s)...\n", args.urls.len(), args.timeout);
let results = check_urls(&args.urls, args.timeout);
print_results(&results, &args.format);
let all_ok = results.iter().all(|r| {
r.error.is_none() && matches!(r.status, Some(200..=299))
});
Ok(all_ok)
}

Keeping process::exit out of run means the pass/fail rule can be tested on its own. The runner fakes four sets of results, so no network is needed, and prints the exit code each would produce.

Try itDecide whether a 301 redirect should count as healthy; if it should, widen the status range and run it again.
Rust (1.40.0)

Complete main.rs

rust
mod checker;
mod output;
use checker::check_urls;
use output::{print_results, OutputFormat};
use std::env;
struct Args {
urls: Vec<String>,
timeout: u64,
format: OutputFormat,
}
fn parse_args() -> Result<Args, String> {
let raw: Vec<String> = env::args().skip(1).collect();
let mut urls = Vec::new();
let mut timeout = 10u64;
let mut format = OutputFormat::Plain;
let mut i = 0;
while i < raw.len() {
match raw[i].as_str() {
"--timeout" => {
i += 1;
timeout = raw.get(i)
.ok_or("--timeout requires a value")?
.parse()
.map_err(|_| "Invalid timeout")?;
}
"--format" => {
i += 1;
format = match raw.get(i).map(String::as_str) {
Some("json") => OutputFormat::Json,
Some("plain") => OutputFormat::Plain,
_ => return Err("--format: plain or json".into()),
};
}
"--help" | "-h" => {
println!("Usage: urlcheck <url>... [--timeout N] [--format plain|json]");
std::process::exit(0);
}
url if url.starts_with("http") => urls.push(url.to_string()),
other => return Err(format!("Unknown: {}", other)),
}
i += 1;
}
if urls.is_empty() { return Err("No URLs provided".into()); }
Ok(Args { urls, timeout, format })
}
fn main() {
let args = match parse_args() {
Ok(a) => a,
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
};
match run(args) {
Ok(true) => {}
Ok(false) => std::process::exit(1), // some checks failed
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
}

Example Output

bash
$ urlcheck http://example.com http://nonexistent.invalid --timeout 5
Checking 2 URLs (timeout: 5s)...
URL Status Time(ms) Error
---------------------------------------------------------------------------
http://example.com 200 85
http://nonexistent.invalid --- 3 DNS lookup failed: ...
Checked 2 URLs: 1 OK, 1 failed, avg response time: 85ms

The timings are from one run and will differ on yours, and the text after DNS lookup failed: comes from your system's resolver. A .invalid name never resolves, so it fails at the lookup rather than timing out.

Key Concept

This capstone is a tour of where Rust earns its keep. Ownership keeps file descriptors and sockets from leaking. Pattern matching forces every case to the surface. Result walks errors back up to main without a single panic-on-purpose, and threads turn a sequential checker into a parallel one. Every concept from the track shows up somewhere in the final binary.

What You Have Built

Your URL health checker is a real tool — install it, drop it in a cron job, point it at your own infrastructure. Under the hood it uses:

  • Ownership & borrowing for safe memory management
  • Enums & pattern matching for command parsing and error handling
  • Traits and generics in the standard library types you used throughout (Option, Result, Vec)
  • Networking with raw TCP sockets
  • Concurrency with threads for parallel URL checking

Where to Go Next

Treat this as scaffolding. Production CLIs in Rust usually pull in:

  • clap for argument parsing
  • reqwest for HTTP with TLS support
  • tokio for async I/O
  • serde for JSON serialisation
  • anyhow for error handling

Every one of those crates sits on top of the primitives you've just walked through by hand. When clap panics or serde rejects a payload, you'll know where to look.

Challenges

Parse command-line style arguments from a vector of strings.

Rust (1.40.0)