Luke M
Use clap to configure your application with defaults, cli args, and env vars
2025-06-10
Clap is a command-line argument parser for Rust that can be used to define arguments for a CLI application. I discovered that it can also read values from the environment variables if no arguments are passed in.
This is so useful, because for local development, I can supply values directly via command-line arguments, while falling back on sensible development defaults. In deployment scenarios, the application can pull from environment variables, set in the container.
Here’s an example Config
struct for an HTTP server, showing how Clap supports development defaults, optional CLI overrides, and environment variable integration:
use clap::Parser;
#[derive(Parser)]
#[command(name = &"My HTTP Server")]
#[command(version, about, long_about = None)]
struct Config {
/// Designates HOST IP address for the API
#[arg(long, env, default_value = &"127.0.0.1")]
pub api_ip: std::net::IpAddr,
/// Designates HOST port for the API.
#[arg(long, env, default_value_t = 58868, value_parser = clap::value_parser!(u16).range(1..))]
pub api_port: u16,
/// List whitelisted IP addresses
///
/// Some API endpoints require elevated privileges, and should only come from certain IP
/// addresses. The format should be a comma-separated string of valid IP addresses, for example;
/// 127.0.0.1,0.0.0.0
#[arg(long, env, num_args = 0.., value_delimiter = ',', default_value = &"127.0.0.1")]
pub api_ip_whitelist: Vec<std::net::IpAddr>,
}
You can then call parse
on the struct.
let config = Config::parse();
This is a very ergonomic way of configuring an application, and one of the examples of why I love working with Rust whenever I have the chance.