gmarche-rs/src/config.rs

46 lines
1.0 KiB
Rust
Raw Normal View History

2020-10-26 23:43:18 +01:00
use serde::{Deserialize, Serialize};
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::Path,
};
2020-12-08 11:05:59 +01:00
const CONFIG_FILE: &str = "config.json";
2020-10-26 23:43:18 +01:00
#[derive(Deserialize, Serialize)]
pub struct Config {
pub admin_passwords: Vec<String>,
pub cookies_https_only: bool,
pub cookies_domain: Option<String>,
pub listen: SocketAddr,
2020-12-17 17:13:11 +01:00
pub root_url: String,
2020-10-26 23:43:18 +01:00
}
impl Default for Config {
fn default() -> Self {
Self {
admin_passwords: vec![],
cookies_https_only: false,
cookies_domain: None,
listen: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 10353),
2020-12-17 17:13:11 +01:00
root_url: String::from("/"),
2020-10-26 23:43:18 +01:00
}
}
}
pub fn read_config(dir: &Path) -> Config {
let path = dir.join(CONFIG_FILE);
if !path.is_file() {
let config = Config::default();
std::fs::write(path, serde_json::to_string_pretty(&config).unwrap())
.expect("Cannot write config file");
config
} else {
serde_json::from_str(
std::str::from_utf8(&std::fs::read(path).expect("Cannot read config file"))
.expect("Bad encoding in config file"),
)
.expect("Bad JSON in config file")
}
}