Skip to main content

cargo_smith/config/
mod.rs

1use std::env;
2use dotenvy::dotenv;
3
4pub struct Config;
5
6impl Config {
7    /// Load .env file (Call this at the very top of main)
8    pub fn init() {
9        if let Err(e) = dotenv() {
10            // We don't panic here because in Production (Docker), 
11            // .env files often don't exist—real env vars are used instead.
12            eprintln!("Note: No .env file loaded: {}", e);
13        }
14    }
15
16    /// Required: Get a string or panic
17    pub fn get(key: &str) -> String {
18        env::var(key).unwrap_or_else(|_| panic!("Environment variable [{}] is missing!", key))
19    }
20
21    /// Optional: Get a string or return a default
22    pub fn get_or(key: &str, default: &str) -> String {
23        env::var(key).unwrap_or_else(|_| default.to_string())
24    }
25
26    /// Typed: Get and parse (e.g., Config::get_as::<u16>("PORT"))
27    pub fn get_as<T>(key: &str) -> T 
28    where 
29        T: std::str::FromStr, 
30        <T as std::str::FromStr>::Err: std::fmt::Debug 
31    {
32        Self::get(key)
33            .parse::<T>()
34            .expect(&format!("❌ Environment variable [{}] is not the correct type!", key))
35    }
36
37    /// Check if a variable exists (useful for feature flags)
38    pub fn has(key: &str) -> bool {
39        env::var(key).is_ok()
40    }
41}