add basic application config and parser

This commit is contained in:
glyph 2022-03-11 10:19:00 +02:00
parent 23d6870f77
commit 6b145d66f8
2 changed files with 56 additions and 0 deletions

2
peach-web/config Normal file
View File

@ -0,0 +1,2 @@
disable_auth=false
standalone_mode=true

54
peach-web/src/config.rs Normal file
View File

@ -0,0 +1,54 @@
// Kind thanks to Alex Wennerberg (https://alexwennerberg.com/) for writing
// this code and offered it under the 0BSD (BDS 0-Clause) license.
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
// Ini-like key=value configuration with global config only (no subsections).
#[derive(Debug)]
pub struct Config {
pub disable_auth: bool,
pub standalone_mode: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
disable_auth: false,
standalone_mode: true,
}
}
}
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(),
_ => {}
}
}
}
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.len() == 0 {
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")
}
}
Ok(conf)
}
}