From 1bdacf36326e3ea1a70fe636fb6b5e4079773560 Mon Sep 17 00:00:00 2001 From: glyph Date: Thu, 24 Mar 2022 09:05:53 +0200 Subject: [PATCH] add application configuration to replace Rocket.toml --- peach-web/src/config.rs | 67 ++++++++++++++++++++--------------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/peach-web/src/config.rs b/peach-web/src/config.rs index 5ea7b93..b1c2e95 100644 --- a/peach-web/src/config.rs +++ b/peach-web/src/config.rs @@ -1,54 +1,53 @@ -// Kind thanks to Alex Wennerberg (https://alexwennerberg.com/) for writing -// this code and offered it under the 0BSD (BDS 0-Clause) license. +//! Define the configuration parameters for the web application. +//! +//! Sets default values and updates them if the corresponding environment +//! variables have been set. -use std::fs::File; -use std::io::{self, BufRead}; -use std::path::Path; +use std::env; + +// environment variable keys to check for +const ENV_VARS: [&str; 4] = ["STANDALONE_MODE", "DISABLE_AUTH", "ADDR", "PORT"]; -// Ini-like key=value configuration with global config only (no subsections). -#[derive(Debug, PartialEq)] pub struct Config { - pub disable_auth: bool, pub standalone_mode: bool, + pub disable_auth: bool, + pub addr: String, + pub port: String, } impl Default for Config { fn default() -> Self { Self { - disable_auth: false, standalone_mode: true, + disable_auth: false, + addr: "127.0.0.1".to_string(), + port: "8000".to_string(), } } } impl Config { - pub fn match_kv(&mut self, key: &str, value: &str) { - match key { - "disable_auth" => self.disable_auth = value.parse().unwrap(), - "standalone_mode" => self.standalone_mode = value.parse().unwrap(), - _ => {} - } - } -} + pub fn new() -> Config { + // define default config values + let mut config = Config::default(); -impl Config { - pub fn from_file>(path: P) -> Result { - let file = File::open(path)?; - let mut conf = Config::default(); - - for l in io::BufReader::new(file).lines() { - let line = l?; - if line.is_empty() { - continue; - } - if let Some(i) = line.find('=') { - let key = &line[..i]; - let value = &line[i + 1..]; - conf.match_kv(key, value); - } else { - // panic!("Invalid config") + // check for the environment variables in our config + for key in ENV_VARS { + // if a variable (key) has been set, check the value + if let Ok(val) = env::var(key) { + // if the value is of the correct type, update the config value + match key { + "STANDALONE_MODE" if val.as_str() == "true" => config.standalone_mode = true, + "STANDALONE_MODE" if val.as_str() == "false" => config.standalone_mode = false, + "DISABLE_AUTH" if val.as_str() == "true" => config.disable_auth = true, + "DISABLE_AUTH" if val.as_str() == "false" => config.disable_auth = false, + "ADDR" => config.addr = val, + "PORT" => config.port = val, + _ => (), + } } } - Ok(conf) + + config } }