-
-
Save ircnelson/01445f738b294f0421cc0dd0de0aae57 to your computer and use it in GitHub Desktop.
Getting configurations in Rust lang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SERVER.PORT=5001 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[dependencies] | |
serde = "1.0.113" | |
serde_derive = "1.0.113" | |
dotenv = "0.15.0" | |
config = "0.10.1" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# settings.toml | |
[server] | |
host = "192.168.0.10" | |
port = 5000 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# settings_development.toml | |
[server] | |
host = "127.0.0.1" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/main.rs | |
mod settings; | |
use crate::settings::Settings; | |
use dotenv::dotenv; | |
fn main() { | |
dotenv().ok(); | |
let config = Settings::new().unwrap(); | |
println!("Server: {}:{}", config.server.host, config.server.port); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/settings.rs | |
use config::{Config, ConfigError, Environment, File}; | |
use serde_derive::Deserialize; | |
use std::env; | |
#[derive(Deserialize)] | |
pub struct ServerSettings { | |
pub host: String, | |
pub port: i32, | |
} | |
#[derive(Deserialize)] | |
pub struct Settings { | |
pub server: ServerSettings, | |
} | |
impl Settings { | |
pub fn new() -> Result<Self, ConfigError> { | |
let env = env::var("environment").unwrap_or("development".into()); | |
let mut cfg = Config::new(); | |
cfg.merge(File::with_name("settings"))?; | |
cfg.merge(File::with_name(&format!("settings_{}", env)).required(false))?; | |
cfg.merge(Environment::new())?; | |
cfg.try_into() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment