|
1 | | -mod settings; |
| 1 | +use std::env; |
2 | 2 |
|
3 | | -use settings::Settings; |
| 3 | +use config::{Config, ConfigError, Environment, File}; |
| 4 | +use serde::Deserialize; |
4 | 5 |
|
5 | 6 | fn main() { |
6 | 7 | let settings = Settings::new(); |
7 | 8 |
|
8 | 9 | // Print out our settings |
9 | 10 | println!("{settings:?}"); |
10 | 11 | } |
| 12 | + |
| 13 | +#[derive(Debug, Deserialize)] |
| 14 | +#[allow(unused)] |
| 15 | +pub(crate) struct Settings { |
| 16 | + debug: bool, |
| 17 | + database: Database, |
| 18 | + sparkpost: Sparkpost, |
| 19 | + twitter: Twitter, |
| 20 | + braintree: Braintree, |
| 21 | +} |
| 22 | + |
| 23 | +impl Settings { |
| 24 | + pub(crate) fn new() -> Result<Self, ConfigError> { |
| 25 | + let run_mode = env::var("RUN_MODE").unwrap_or_else(|_| "development".into()); |
| 26 | + |
| 27 | + let s = Config::builder() |
| 28 | + // Start off by merging in the "default" configuration file |
| 29 | + .add_source(File::with_name("examples/hierarchical-env/config/default")) |
| 30 | + // Add in the current environment file |
| 31 | + // Default to 'development' env |
| 32 | + // Note that this file is _optional_ |
| 33 | + .add_source( |
| 34 | + File::with_name(&format!("examples/hierarchical-env/config/{run_mode}")) |
| 35 | + .required(false), |
| 36 | + ) |
| 37 | + // Add in a local configuration file |
| 38 | + // This file shouldn't be checked in to git |
| 39 | + .add_source(File::with_name("examples/hierarchical-env/config/local").required(false)) |
| 40 | + // Add in settings from the environment (with a prefix of APP) |
| 41 | + // Eg.. `APP_DEBUG=1 ./target/app` would set the `debug` key |
| 42 | + .add_source(Environment::with_prefix("APP")) |
| 43 | + // You may also programmatically change settings |
| 44 | + .set_override("database.url", "postgres://")? |
| 45 | + .build()?; |
| 46 | + |
| 47 | + // Now that we're done, let's access our configuration |
| 48 | + println!("debug: {:?}", s.get_bool("debug")); |
| 49 | + println!("database: {:?}", s.get::<String>("database.url")); |
| 50 | + |
| 51 | + // You can deserialize (and thus freeze) the entire configuration as |
| 52 | + s.try_deserialize() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +#[derive(Debug, Deserialize)] |
| 57 | +#[allow(unused)] |
| 58 | +struct Database { |
| 59 | + url: String, |
| 60 | +} |
| 61 | + |
| 62 | +#[derive(Debug, Deserialize)] |
| 63 | +#[allow(unused)] |
| 64 | +struct Sparkpost { |
| 65 | + key: String, |
| 66 | + token: String, |
| 67 | + url: String, |
| 68 | + version: u8, |
| 69 | +} |
| 70 | + |
| 71 | +#[derive(Debug, Deserialize)] |
| 72 | +#[allow(unused)] |
| 73 | +struct Twitter { |
| 74 | + consumer_token: String, |
| 75 | + consumer_secret: String, |
| 76 | +} |
| 77 | + |
| 78 | +#[derive(Debug, Deserialize)] |
| 79 | +#[allow(unused)] |
| 80 | +struct Braintree { |
| 81 | + merchant_id: String, |
| 82 | + public_key: String, |
| 83 | + private_key: String, |
| 84 | +} |
0 commit comments