From 64aec75659df4b9fcb378386e64cdabe58af5265 Mon Sep 17 00:00:00 2001 From: Edward Shen Date: Sat, 21 Dec 2019 14:16:47 -0500 Subject: [PATCH] refactor config reading --- src/main.rs | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/src/main.rs b/src/main.rs index e080de4..ee2d12a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -120,22 +120,8 @@ struct State { } fn main() -> Result<(), Error> { - let config_file = match File::open(CONFIG_FILE) { - Ok(file) => file, - Err(_) => { - eprintln!("Unable to find a {} file. Creating default!", CONFIG_FILE); - let mut fd = OpenOptions::new() - .write(true) - .create_new(true) - .open(CONFIG_FILE) - .expect("Unable to write to directory!"); - fd.write_all(DEFAULT_CONFIG)?; - File::open(CONFIG_FILE)? - } - }; - + let conf = read_config(CONFIG_FILE)?; let renderer = compile_templates(); - let conf: Config = serde_yaml::from_reader(config_file).unwrap(); let state = Arc::from(RwLock::new(State { public_address: conf.public_address, default_route: conf.default_route, @@ -150,10 +136,8 @@ fn main() -> Result<(), Error> { watch .watch(CONFIG_FILE, move |e: Event| { if let Event::Write(_) = e { - let config_file = File::open(CONFIG_FILE).unwrap(); - let conf: Config = serde_yaml::from_reader(config_file).unwrap(); - let state = state.clone(); let mut state = state.write().unwrap(); + let conf = read_config(CONFIG_FILE).unwrap(); state.public_address = conf.public_address; state.default_route = conf.default_route; state.routes = conf.routes; @@ -173,6 +157,26 @@ fn main() -> Result<(), Error> { .run() } +fn read_config(config_file_path: &str) -> Result { + let config_file = match File::open(config_file_path) { + Ok(file) => file, + Err(_) => { + eprintln!( + "Unable to find a {} file. Creating default!", + config_file_path + ); + let mut fd = OpenOptions::new() + .write(true) + .create_new(true) + .open(config_file_path) + .expect("Unable to write to directory!"); + fd.write_all(DEFAULT_CONFIG)?; + File::open(config_file_path)? + } + }; + Ok(serde_yaml::from_reader(config_file).unwrap()) +} + fn compile_templates() -> Handlebars { let mut handlebars = Handlebars::new(); handlebars