refactor config reading

This commit is contained in:
Edward Shen 2019-12-21 14:16:47 -05:00
parent c195efd1b4
commit 64aec75659
Signed by: edward
GPG key ID: F350507060ED6C90

View file

@ -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<Config, Error> {
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