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