From 0f427ba1d1121664af7909aa7311fec7d95e1391 Mon Sep 17 00:00:00 2001 From: Sandro Eiler Date: Wed, 7 Feb 2024 13:40:54 +0100 Subject: [PATCH] refactor: enhance env variable usage --- Cargo.lock | 12 ++++++++++++ Cargo.toml | 1 + src/configuration.rs | 8 ++++++++ 3 files changed, 21 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 279f355..fd82480 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1046,6 +1046,7 @@ dependencies = [ "reqwest", "secrecy", "serde", + "serde-aux", "serde_json", "sqlx", "tokio", @@ -1849,6 +1850,17 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-aux" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a86348501c129f3ad50c2f4635a01971f76974cd8a3f335988a0f1581c082765" +dependencies = [ + "chrono", + "serde", + "serde_json", +] + [[package]] name = "serde_derive" version = "1.0.193" diff --git a/Cargo.toml b/Cargo.toml index 37eb1e1..2a34523 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ hyper = { version = "1.1.0", features = ["full"] } # Serde / json serde = { version = "1.0", features = ["derive"] } serde_json = "1" +serde-aux = "4" # serde_with = "3" # Axum axum = { version = "0.7" } diff --git a/src/configuration.rs b/src/configuration.rs index 4c7c463..3f419b7 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -1,4 +1,5 @@ use secrecy::{ExposeSecret, Secret}; +use serde_aux::field_attributes::deserialize_number_from_string; #[derive(serde::Deserialize)] /// The setting collection. @@ -16,6 +17,7 @@ pub struct Settings { /// * `port`: The port to listen on /// * `host`: The host address to listen on pub struct ApplicationSettings { + #[serde(deserialize_with = "deserialize_number_from_string")] pub port: u16, pub host: String, } @@ -31,6 +33,7 @@ pub struct ApplicationSettings { pub struct DatabaseSettings { pub username: String, pub password: Secret, + #[serde(deserialize_with = "deserialize_number_from_string")] pub port: u16, pub host: String, pub name: String, @@ -88,6 +91,11 @@ pub fn get_configuration() -> Result { .add_source(config::File::from( configuration_directory.join(environment_filename), )) + .add_source( + config::Environment::with_prefix("APP") + .prefix_separator("_") + .separator("__"), + ) .build()?; settings.try_deserialize::()