From e755cc4b45356b0484eb9254b4a0647cdca1591e Mon Sep 17 00:00:00 2001 From: Serguey Parkhomovsky Date: Sat, 21 Mar 2026 11:29:28 -0700 Subject: Add bind arg and better error handling --- README.md | 22 +++++++++++++++++++++- src/main.rs | 12 ++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e598e7d..7d463a3 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,27 @@ Or directly: cargo run ``` -The server listens on `0.0.0.0:3000`. +By default the server listens on `0.0.0.0:3000` and reads config from `config.toml`. + +## CLI Arguments + +| Argument | Default | Description | +|----------|---------|-------------| +| `--config ` | `config.toml` | Path to the configuration file | +| `--bind ` | `0.0.0.0:3000` | Address to bind the HTTP server to | + +Examples: + +```sh +# Use a custom config file +./target/release/printstats --config /etc/printstats/config.toml + +# Listen on a different address/port +./target/release/printstats --bind 127.0.0.1:8080 + +# Both at once +./target/release/printstats --config /etc/printstats/config.toml --bind 127.0.0.1:8080 +``` ## API diff --git a/src/main.rs b/src/main.rs index 187c0fe..5337fc3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,10 @@ struct Args { /// Path to the configuration file #[arg(long, default_value = "config.toml")] config: String, + + /// Address to bind the HTTP server to + #[arg(long, default_value = "0.0.0.0:3000")] + bind: String, } #[tokio::main] @@ -26,7 +30,8 @@ async fn main() { tracing_subscriber::fmt::init(); let args = Args::parse(); - let content = fs::read_to_string(&args.config).expect("Couldn't read config file"); + let content = fs::read_to_string(&args.config) + .unwrap_or_else(|e| panic!("Failed to read '{}': {}", args.config, e)); let config = Config::load(&content); let state: StateMap = Arc::new(Mutex::new(HashMap::new())); let mut tasks = JoinSet::new(); @@ -80,7 +85,10 @@ async fn main() { let app = Router::new().route("/", get(root)).with_state(state); - let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + let listener = tokio::net::TcpListener::bind(&args.bind) + .await + .unwrap_or_else(|e| panic!("Failed to bind to '{}': {}", args.bind, e)); + println!("Listening on {}", args.bind); axum::serve(listener, app).await.unwrap(); } -- cgit v1.2.3