A simple way to decode configuration files based on the current application environment into globally accessible variables
The code for Rust Global Configuration Files with Multiple Environments
A simple way to decode configuration files based on the current application environment into globally accessible variables
The code for Rust Global Configuration Files with Multiple Environments
[package] | |
name = "myapp" | |
version = "0.1.0" | |
authors = ["Ibraheem Ahmed <ibrah1440@gmail.com>"] | |
edition = "2018" | |
[dependencies] | |
serde = { version = "1.0.116", features = ["derive"] } | |
serde_yaml = "0.8" | |
lazy_static = "1.4.0" |
// src/config.rs | |
use serde::Deserialize; | |
use std::{env, fs, io}; | |
pub static CONFIG_DIR: &str = "config/"; | |
pub static APP_ENV: &str = "APP_ENV"; | |
#[derive(Debug, Deserialize, Clone)] | |
pub struct Config { | |
database: DatabaseConfig, | |
} | |
#[derive(Debug, Deserialize, Clone)] | |
pub struct DatabaseConfig { | |
user: String, | |
password: String, | |
host: String, | |
port: i32, | |
database: String, | |
} | |
lazy_static! { | |
static ref CONFIG: Config = Config::init(); | |
} | |
impl Config { | |
fn init() -> Self { | |
let env = Config::get_environment(); | |
let env = match env { | |
Ok(e) => match e.as_ref() { | |
"development" | "testing" | "production" => e, | |
_ => String::from("development"), | |
}, | |
Err(_) => String::from("development"), | |
}; | |
let contents = Self::read_config_file(env.as_ref()).unwrap(); | |
return serde_yaml::from_str(&contents).unwrap(); | |
} | |
pub fn get() -> Self { | |
CONFIG.to_owned() | |
} | |
pub fn read_config_file(env: &str) -> Result<String, io::Error> { | |
fs::read_to_string(format!("{}{}.yml", CONFIG_DIR, env)) | |
} | |
pub fn get_environment() -> Result<String, env::VarError> { | |
env::var(APP_ENV) | |
} | |
} |
# config/environments/{development, production, testing}.yml | |
database: | |
user: "" | |
password: "" | |
host: "localhost" | |
port: 8080 | |
database: "mytribe" |
// src/main.rs | |
mod config; | |
mod error; | |
#[macro_use] | |
extern crate lazy_static; | |
fn main() { | |
let config = config::Config::get(); | |
println!("{:#?}", config); | |
println!("{:#?}", config.get_database_url()); | |
} |