From d1aec285341254c1749295b77b2ec6a52c09aa04 Mon Sep 17 00:00:00 2001 From: Barry Botha Date: Sun, 5 Oct 2025 18:33:30 +0300 Subject: [PATCH] feat(config): add dotenv support; prefer env over config.toml; add .env.example; fix db_user default --- .env.example | 20 ++++++++++++++++++++ Cargo.toml | 1 + src/utils.rs | 10 ++++++++-- 3 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..335f26f --- /dev/null +++ b/.env.example @@ -0,0 +1,20 @@ +# Example environment configuration for Valence +# Copy to .env and adjust values as needed + +DEBUG=true +EXTERN_PORT=8081 + +DB_PROTOCOL=mongodb:// +DB_URL=localhost +DB_PORT=27017 +DB_USER=root +DB_PASSWORD=example + +CACHE_URL=redis://localhost +CACHE_PORT=6379 +CACHE_PASSWORD=secret + +BODY_LIMIT=8192 +CACHE_TTL=900 + +MARKET=false diff --git a/Cargo.toml b/Cargo.toml index 840f1d9..714dd44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ edition = "2021" async-trait = "0.1.73" chrono = "0.4.26" config = "0.13.3" +dotenvy = "0.15.7" cuckoofilter = "0.5.0" futures = "0.3.28" hex = "0.4.3" diff --git a/src/utils.rs b/src/utils.rs index e26833b..5d650fb 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -170,7 +170,13 @@ pub async fn init_cuckoo_filter( /// Loads the config file pub fn load_config() -> EnvConfig { - let settings = config::Config::builder().add_source(config::File::with_name(CONFIG_FILE)); + // Load variables from a .env file into process environment if present + dotenvy::dotenv().ok(); + + // File-sourced config first, then environment with higher precedence + let settings = config::Config::builder() + .add_source(config::File::with_name(CONFIG_FILE)) + .add_source(config::Environment::default()); match settings.build() { Ok(config) => EnvConfig { @@ -183,7 +189,7 @@ pub fn load_config() -> EnvConfig { .unwrap_or(SETTINGS_DB_URL.to_string()), db_user: config .get_string("db_user") - .unwrap_or(SETTINGS_DB_URL.to_string()), + .unwrap_or(SETTINGS_DB_USER.to_string()), db_protocol: config .get_string("db_protocol") .unwrap_or(SETTINGS_DB_PROTOCOL.to_string()),