From 5928f5b0b5eee50e08a4b9f5a9fa739f7f7adc4f Mon Sep 17 00:00:00 2001 From: antifallobst Date: Thu, 23 Nov 2023 23:11:39 +0100 Subject: [PATCH] feat: added automatic runtime env variable existence checker --- src/main.rs | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index af02ad1..67609c3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,22 +16,26 @@ async fn main() -> Result<()> { let port: u16 = 8080; - let pool = PgPool::connect(&std::env::var("DATABASE_URL").map_err(|_| { - anyhow::Error::msg("Environment variable DATABASE_URL needs to be specified!") - })?) - .await?; + check_envs(vec![ + "DATABASE_URL", + "SMTP_PASSWORD", + "SMTP_HOST_URL", + "SMTP_USER", + "SMTP_PASSWORD", + ])?; - let _ = &std::env::var("SMTP_HOST_URL").map_err(|_| { - anyhow::Error::msg("Environment variable SMTP_HOST_URL needs to be specified!") - })?; - let _ = &std::env::var("SMTP_USER").map_err(|_| { - anyhow::Error::msg("Environment variable SMTP_HOST_URL needs to be specified!") - })?; - let _ = &std::env::var("SMTP_PASSWORD").map_err(|_| { - anyhow::Error::msg("Environment variable SMTP_HOST_URL needs to be specified!") - })?; + let pool = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await?; api::start(port, pool).await?; Ok(()) } + +fn check_envs(envs: Vec<&str>) -> Result<()> { + for env in envs { + let _ = &std::env::var(env).map_err(|_| { + anyhow::Error::msg(format!("Environment variable {env} needs to be set!")) + })?; + } + Ok(()) +}