gmarche-rs/src/config.rs

75 lines
1.8 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 {
2020-12-18 08:26:30 +01:00
#[serde(default = "Config::default_admin_passwords")]
2020-10-26 23:43:18 +01:00
pub admin_passwords: Vec<String>,
2020-12-18 08:26:30 +01:00
#[serde(default = "Config::default_cookies_https_only")]
2020-10-26 23:43:18 +01:00
pub cookies_https_only: bool,
2020-12-18 08:26:30 +01:00
#[serde(default = "Config::default_cookies_domain")]
2020-10-26 23:43:18 +01:00
pub cookies_domain: Option<String>,
2020-12-18 08:26:30 +01:00
#[serde(default = "Config::default_listen")]
2020-10-26 23:43:18 +01:00
pub listen: SocketAddr,
2020-12-18 08:26:30 +01:00
#[serde(default = "Config::default_root_url")]
2020-12-17 17:13:11 +01:00
pub root_url: String,
2020-12-18 08:26:30 +01:00
#[serde(default = "Config::default_title")]
2020-12-17 23:08:31 +01:00
pub title: String,
2020-10-26 23:43:18 +01:00
}
2020-12-18 08:26:30 +01:00
impl Config {
fn default_admin_passwords() -> Vec<String> {
vec![]
}
fn default_cookies_https_only() -> bool {
false
}
fn default_cookies_domain() -> Option<String> {
None
}
fn default_listen() -> SocketAddr {
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 10353)
}
fn default_root_url() -> String {
"/".into()
}
fn default_title() -> String {
"ĞMarché".into()
}
}
2020-10-26 23:43:18 +01:00
impl Default for Config {
fn default() -> Self {
Self {
2020-12-18 08:26:30 +01:00
admin_passwords: Self::default_admin_passwords(),
cookies_https_only: Self::default_cookies_https_only(),
cookies_domain: Self::default_cookies_domain(),
listen: Self::default_listen(),
root_url: Self::default_root_url(),
title: Self::default_title(),
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")
}
}