diff options
Diffstat (limited to 'src/config.rs')
-rw-r--r-- | src/config.rs | 56 |
1 files changed, 44 insertions, 12 deletions
diff --git a/src/config.rs b/src/config.rs index b3c9715..da65385 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,22 +1,54 @@ +use crate::TwinHError; use once_cell::sync::Lazy; -use std::{env::var, error::Error, net::SocketAddr}; +use std::{env, error::Error, net::IpAddr, net::Ipv4Addr, net::SocketAddr}; -pub static CONFIG_INSTANCE: Lazy<AppConfig> = - Lazy::new(|| AppConfig::from_env().expect("Error loading config")); +pub static CONFIG_INSTANCE: Lazy<Config> = Lazy::new(|| match Config::new() { + Ok(c) => c, + Err(e) => panic!("twinh: config error: {}", e), +}); #[derive(Clone, Debug)] -pub struct AppConfig { - pub addr: SocketAddr, - pub db_uri: String, +pub struct Config { + pub bind_addr: SocketAddr, + pub db_path: String, } -impl AppConfig { - pub fn from_env() -> Result<Self, Box<dyn Error>> { - let new = Self { - addr: var("TWINH_ADDR")?.parse()?, - db_uri: var("TWINH_DB_URI")?, +impl Default for Config { + fn default() -> Self { + Self { + bind_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5353), + db_path: String::from("/var/db/twinh"), + } + } +} + +impl Config { + fn new() -> Result<Self, Box<dyn Error>> { + let mut args = env::args().skip(1); + + let db_path = args + .next() + .ok_or_else(|| TwinHError(String::from("database directory not provided")))?; + + let mut config = Config { + bind_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5353), + db_path, }; - Ok(new) + while let Some(arg) = args.next() { + match arg.as_str() { + "--addr" => { + let addr = args.next().unwrap_or_default().parse()?; + config.bind_addr.set_ip(addr); + } + "--port" => { + let port = args.next().unwrap_or_default().parse()?; + config.bind_addr.set_port(port); + } + _ => {} + }; + } + + Ok(config) } } |