add application configuration to replace Rocket.toml

This commit is contained in:
glyph 2022-03-24 09:05:53 +02:00
parent deaedc4428
commit 1bdacf3632
1 changed files with 33 additions and 34 deletions

View File

@ -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<P: AsRef<Path>>(path: P) -> Result<Config, std::io::Error> {
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
}
}