From 4854531d60ad2c68ccdbf19eed6fe9a6ce1b6797 Mon Sep 17 00:00:00 2001 From: Joris Date: Sat, 19 Aug 2023 15:07:10 +0200 Subject: Use environment variables instead of config file --- src/model/config.rs | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) (limited to 'src/model') diff --git a/src/model/config.rs b/src/model/config.rs index e69b4c4..1fa5bb4 100644 --- a/src/model/config.rs +++ b/src/model/config.rs @@ -1,8 +1,42 @@ -use serde::Deserialize; +use std::env; +use std::net::SocketAddr; +use std::str::FromStr; -#[derive(Clone, Deserialize)] +#[derive(Clone)] pub struct Config { - pub secure_cookies: bool, - pub mock_mails: bool, pub auth_secret: String, + pub db_path: String, + pub mock_mails: bool, + pub secure_cookies: bool, + pub socket_address: SocketAddr, +} + +pub fn from_env() -> Result { + Ok(Config { + auth_secret: read_string("AUTH_SECRET")?, + db_path: read_string("DB_PATH")?, + mock_mails: read_bool("MOCK_MAILS")?, + secure_cookies: read_bool("SECURE_COOKIES")?, + socket_address: read_socket_address("SOCKET_ADDRESS")?, + }) +} + +fn read_socket_address(key: &str) -> Result { + SocketAddr::from_str(&read_string(key)?).map_err(|err| { + format!("environment variable '{key}' is not a socket address: {err}") + }) +} + +fn read_bool(key: &str) -> Result { + read_string(key).and_then(|v| match v.as_str() { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(format!( + "environment variable '{key}' is not a boolean: '{v}'" + )), + }) +} + +fn read_string(key: &str) -> Result { + env::var(key).map_err(|_| format!("missing environment variable '{key}'")) } -- cgit v1.2.3