Don't panic!

This commit is contained in:
Mo 2022-10-29 19:09:56 +02:00
parent 635e7e4266
commit c25d431cf3
2 changed files with 26 additions and 14 deletions

View file

@ -1,3 +1,4 @@
use anyhow::{Context, Result};
use serde::Deserialize; use serde::Deserialize;
use std::env; use std::env;
use std::fs::File; use std::fs::File;
@ -26,18 +27,17 @@ pub struct Config {
} }
impl Config { impl Config {
pub fn new() -> Self { pub fn new() -> Result<Self> {
let config_file_var = "CF_CONFIG_FILE"; let config_file_var = "CF_CONFIG_FILE";
let config_path = env::var(config_file_var) 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| { let config_file = File::open(&config_path)
panic!("Can not open the config file at the path {config_path}: {e}") .with_context(|| format!("Can not open the config file at the path {config_path}"))?;
});
let config_reader = BufReader::new(config_file); let config_reader = BufReader::new(config_file);
let config: Self = let config: Self = serde_json::from_reader(config_reader)
serde_json::from_reader(config_reader).expect("Can not parse the config file as JSON!"); .context("Can not parse the config file as JSON!")?;
config Ok(config)
} }
} }

View file

@ -5,19 +5,31 @@ mod forms;
mod mailer; mod mailer;
mod routes; mod routes;
use anyhow::Result;
use rocket::{Build, Rocket};
use rocket_dyn_templates::Template; use rocket_dyn_templates::Template;
use std::process;
#[rocket::launch] fn init() -> Result<Rocket<Build>> {
fn rocket() -> _ { let mut config = config::Config::new()?;
let mut config = config::Config::new();
rocket::build() let rocket = rocket::build()
.mount( .mount(
&config.path_prefix, &config.path_prefix,
rocket::routes![routes::index, routes::submit, routes::success], rocket::routes![routes::index, routes::submit, routes::success],
) )
.manage(captcha_solutions::SharedCaptchaSolutions::new()) .manage(captcha_solutions::SharedCaptchaSolutions::new())
.manage(mailer::Mailer::new(&mut config).expect("Failed to create mailer!")) .manage(mailer::Mailer::new(&mut config)?)
.manage(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);
})
} }