From a02114f9ea17e0161b2b334c1c57bac451a70266 Mon Sep 17 00:00:00 2001 From: Ryan Leckey Date: Fri, 16 Jun 2017 11:45:35 -0700 Subject: Add hierarchial config example --- examples/hierarchical-env/src/settings.rs | 70 +++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 examples/hierarchical-env/src/settings.rs (limited to 'examples/hierarchical-env/src/settings.rs') diff --git a/examples/hierarchical-env/src/settings.rs b/examples/hierarchical-env/src/settings.rs new file mode 100644 index 0000000..43897b3 --- /dev/null +++ b/examples/hierarchical-env/src/settings.rs @@ -0,0 +1,70 @@ +use std::env; +use config::{Config, File, Environment}; + +#[derive(Debug, Deserialize)] +struct Database { + url: String, +} + +#[derive(Debug, Deserialize)] +struct Sparkpost { + key: String, + token: String, + url: String, + version: u8, +} + +#[derive(Debug, Deserialize)] +struct Twitter { + consumer_token: String, + consumer_secret: String, +} + +#[derive(Debug, Deserialize)] +struct Braintree { + merchant_id: String, + public_key: String, + private_key: String, +} + +#[derive(Debug, Deserialize)] +pub struct Settings { + debug: bool, + database: Database, + sparkpost: Sparkpost, + twitter: Twitter, + braintree: Braintree, +} + +impl Settings { + pub fn new() -> Self { + let mut s = Config::new(); + + // Start off by merging in the "default" configuration file + s.merge(File::with_name("config/default")).unwrap(); + + // Add in the current environment file + // Default to 'development' env + // Note that this file is _optional_ + let env = env::var("RUN_MODE").unwrap_or("development".into()); + s.merge(File::with_name(&format!("config/{}", env)).required(false)).unwrap(); + + // Add in a local configuration file + // This file shouldn't be checked in to git + s.merge(File::with_name("config/local").required(false)).unwrap(); + + // Add in settings from the environment (with a prefix of APP) + // Eg.. `APP_DEBUG=1 ./target/app` would set the `debug` key + s.merge(Environment::with_prefix("app")).unwrap(); + + // You may also programmatically change settings + s.set("database.url", "postgres://").unwrap(); + + // Now that we're done, let's access our configuration + println!("debug: {:?}", s.get_bool("debug")); + println!("database: {:?}", s.get::("database.url")); + + // You can deserialize (and thus freeze) the entire configuration as + s.deserialize().unwrap() + } +} -- cgit v1.2.3