From f9726f7b35e224bf6b3c3ac878d15e088395a00f Mon Sep 17 00:00:00 2001 From: AINDUSTRIES Date: Fri, 24 Oct 2025 12:13:02 +0200 Subject: [PATCH] Added command line argument for the config file location --- Cargo.toml | 3 ++- src/main.rs | 39 ++++++++++++++++++++++++++++++++------- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 73cd65e..d4710e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,4 +9,5 @@ serde = "1.0.228" serde_json = "1.0.145" toml = "0.9.7" sqlx = {version = "0.8.6", features = ["postgres"]} -futures-util = "0.3.31" \ No newline at end of file +futures-util = "0.3.31" +clap = { version = "4.5.50", features = ["derive"] } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index dcb548f..5f64ca6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,9 +3,11 @@ mod middleware; mod pages; use actix_web::{App, HttpServer, web}; +use clap::Parser; use serde::Deserialize; use std::fs::File; use std::io::Read; +use std::process::exit; use toml::from_slice; use middleware::MimeType; @@ -15,6 +17,13 @@ use pages::{ projects::{project, projects}, }; +#[derive(Parser)] +#[command(name = "aindustries-be", version, about = "This is the amazing webserver for aindustries.be!", long_about = None)] +struct Cli { + #[arg(short, long, value_name = "CONFIG", help = "Path to config file, defaults to /etc/aindustries-be/config.toml")] + config: Option, +} + #[derive(Deserialize)] struct Config { server: ServerConfig, @@ -32,13 +41,29 @@ struct AppState { #[actix_web::main] async fn main() { - let mut config_file = - File::open("/etc/aindustries-be/config.toml").expect("Could not open config file"); + let cli = Cli::parse(); + let config_file_path = cli + .config + .unwrap_or("/etc/aindustries-be/config.toml".to_string()); + let mut config_file = match File::open(&config_file_path) { + Ok(config_file) => config_file, + Err(e) => { + eprintln!("Could not open config file ({config_file_path}): {e}"); + exit(1); + } + }; let mut buf = vec![]; - config_file - .read_to_end(&mut buf) - .expect("Could not read config file"); - let config: Config = from_slice(&buf).expect("Could not parse config"); + if let Err(e) = config_file.read_to_end(&mut buf) { + eprintln!("Could not read config file: {e}"); + exit(1); + } + let config: Config = match from_slice(&buf) { + Ok(config) => config, + Err(e) => { + eprintln!("Could not parse config file {e}"); + exit(1); + } + }; let bind_address = config.server.bind; let assets = config.server.assets; let data = web::Data::new(AppState { assets }); @@ -56,7 +81,7 @@ async fn main() { match server.run().await { Ok(_) => {} Err(e) => { - eprintln!("An error occurred: {}", e); + eprintln!("An error occurred: {e}"); } } }