diff --git a/src/config.rs b/src/config.rs index 71bec9d..600f120 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,3 +1,4 @@ +use anyhow::{Context, Result}; use serde::Deserialize; use std::env; use std::fs::File; @@ -26,18 +27,17 @@ pub struct Config { } impl Config { - pub fn new() -> Self { + pub fn new() -> Result { let config_file_var = "CF_CONFIG_FILE"; let config_path = env::var(config_file_var) - .unwrap_or_else(|_| panic!("Environment variable {config_file_var} missing!")); + .with_context(|| format!("Environment variable {config_file_var} missing!"))?; - let config_file = File::open(&config_path).unwrap_or_else(|e| { - panic!("Can not open the config file at the path {config_path}: {e}") - }); + let config_file = File::open(&config_path) + .with_context(|| format!("Can not open the config file at the path {config_path}"))?; let config_reader = BufReader::new(config_file); - let config: Self = - serde_json::from_reader(config_reader).expect("Can not parse the config file as JSON!"); + let config: Self = serde_json::from_reader(config_reader) + .context("Can not parse the config file as JSON!")?; - config + Ok(config) } } diff --git a/src/main.rs b/src/main.rs index 51d0c76..3b1932a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,19 +5,31 @@ mod forms; mod mailer; mod routes; +use anyhow::Result; +use rocket::{Build, Rocket}; use rocket_dyn_templates::Template; +use std::process; -#[rocket::launch] -fn rocket() -> _ { - let mut config = config::Config::new(); +fn init() -> Result> { + let mut config = config::Config::new()?; - rocket::build() + let rocket = rocket::build() .mount( &config.path_prefix, rocket::routes![routes::index, routes::submit, routes::success], ) .manage(captcha_solutions::SharedCaptchaSolutions::new()) - .manage(mailer::Mailer::new(&mut config).expect("Failed to create mailer!")) + .manage(mailer::Mailer::new(&mut config)?) .manage(config) - .attach(Template::fairing()) + .attach(Template::fairing()); + + Ok(rocket) +} + +#[rocket::launch] +fn rocket() -> _ { + init().unwrap_or_else(|e| { + eprintln!("{e}"); + process::exit(1); + }) }