diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..c7ba133 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,28 @@ +use std::{env, sync::OnceLock}; + +use dotenvy::dotenv; + +static CONFIG: OnceLock = OnceLock::new(); + +pub struct Config { + pub zauth_url: String, + pub db_uri: String, +} + +impl Config { + pub fn initialize() { + assert!(CONFIG.get().is_none()); + + Config::get(); + } + + pub fn get() -> &'static Config { + CONFIG.get_or_init(|| { + dotenv().ok(); + Config { + db_uri: env::var("DATABASE_URL").expect("DATABASE_URL must be set"), + zauth_url: env::var("ZAUTH_URL").expect("ZAUTH_URL must be set"), + } + }) + } +} diff --git a/src/db/lib.rs b/src/db/lib.rs index 30de47d..c27c753 100644 --- a/src/db/lib.rs +++ b/src/db/lib.rs @@ -1,9 +1,10 @@ use diesel::prelude::*; use diesel::sqlite::SqliteConnection; -use std::env; + +use crate::config::Config; pub fn establish_connection() -> SqliteConnection { - let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); + let database_url = Config::get().db_uri.clone(); SqliteConnection::establish(&database_url) - .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) + .unwrap_or_else(|_| panic!("Error connecting to {}", Config::get().db_uri)) } diff --git a/src/handlers/update/authenticate.rs b/src/handlers/update/authenticate.rs index 323a901..ed68bb1 100644 --- a/src/handlers/update/authenticate.rs +++ b/src/handlers/update/authenticate.rs @@ -1,8 +1,6 @@ -use std::env; - use reqwest::Error; -use crate::errors::AuthenticationError; +use crate::{config::Config, errors::AuthenticationError}; use super::sig::{PublicKey, Sig}; @@ -38,11 +36,12 @@ pub(super) async fn authenticate(sig: &Sig, zone: &Vec) -> Result } async fn get_keys(username: &String) -> std::result::Result { - let zauth_url = env::var("ZAUTH_URL").expect("ZAUTH_URL must be set"); - Ok( - reqwest::get(format!("{}/users/keys/{}", zauth_url, username)) - .await? - .json::() - .await?, - ) + Ok(reqwest::get(format!( + "{}/users/keys/{}", + Config::get().zauth_url, + username + )) + .await? + .json::() + .await?) } diff --git a/src/main.rs b/src/main.rs index baac33b..f4a036f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,10 @@ use std::{error::Error, net::SocketAddr}; -use dotenvy::dotenv; +use config::Config; use crate::resolver::resolver_listener_loop; +mod config; mod db; mod errors; mod handlers; @@ -16,8 +17,7 @@ mod utils; #[tokio::main] async fn main() -> Result<(), Box> { - dotenv().ok(); - + Config::initialize(); let resolver_add = SocketAddr::from(([127, 0, 0, 1], 8080)); let _ = tokio::join!(resolver_listener_loop(resolver_add),); Ok(())