From c7d885e4b8189e4539c1f259a44ec37c6cd027b2 Mon Sep 17 00:00:00 2001 From: "Adam T. Carpenter" Date: Mon, 2 May 2022 22:32:52 -0400 Subject: feat: reset button read config start db pool and launch axum server --- dichroism/src/config.rs | 62 +++++++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 23 deletions(-) (limited to 'dichroism/src/config.rs') diff --git a/dichroism/src/config.rs b/dichroism/src/config.rs index 2031ecc..225ee4c 100644 --- a/dichroism/src/config.rs +++ b/dichroism/src/config.rs @@ -1,32 +1,48 @@ -use crate::constants::DEFAULT_CONFIG; use crate::result::Result; -use once_cell::sync::Lazy; -use serde::Deserialize; -use std::env::var; -use std::fs::File; -use std::io::prelude::*; -use std::net::SocketAddr; -use toml::from_str; +use anyhow::{anyhow, Context}; +use std::{env::var, net::SocketAddr, path::PathBuf}; -pub static CONFIG_INSTANCE: Lazy = Lazy::new(|| { - Config::from_toml().unwrap_or_else(|e| { - eprintln!("Error parsing config: {}", e.to_string()); - std::process::exit(1); - }) -}); - -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone)] pub struct Config { - pub db_url: String, - pub img_root: String, pub bind_addr: SocketAddr, + pub db_path: PathBuf, + pub img_path: PathBuf, } impl Config { - pub fn from_toml() -> Result { - let path = var("DICHROISM_CONFIG").unwrap_or_else(|_| String::from(DEFAULT_CONFIG)); - let mut config = String::new(); - File::open(path)?.read_to_string(&mut config)?; - Ok(from_str(&config)?) + pub fn from_env() -> Result { + let config = Self { + bind_addr: var("GL_BIND_ADDR") + .with_context(|| "Bind address missing.")? + .parse() + .with_context(|| "Failed to parse bind address.")?, + db_path: var("GL_DB_PATH") + .with_context(|| "Database path missing.")? + .parse() + .with_context(|| "Failed to parse database path.")?, + img_path: var("GL_IMG_PATH") + .with_context(|| "Image store path missing.")? + .parse() + .with_context(|| "Failed to parse image store path.")?, + }; + + if config.db_path.is_dir() { + Err(anyhow!(format!( + "Database path {:?} is not a regular file", + config.db_path + ))) + } else if !config.img_path.is_dir() { + Err(anyhow!(format!( + "Image store path {:?} is not a directory.", + config.img_path + ))) + } else if config.img_path.read_dir().is_err() { + Err(anyhow!(format!( + "Image store path {:?} is not readable.", + config.img_path + ))) + } else { + Ok(config) + } } } -- cgit v1.2.3