Moved some config over to an actual config file, improved error handling

This commit is contained in:
2022-12-24 04:44:34 +01:00
parent 7e3c3223b2
commit 1299443a7c
6 changed files with 64 additions and 17 deletions

29
src/config.rs Normal file
View File

@@ -0,0 +1,29 @@
use std::{fs, error::Error};
use log::debug;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Config {
pub mqtt: MQTT,
}
#[derive(Debug, Deserialize)]
pub struct MQTT {
pub host: String,
pub port: u16,
pub username: String,
pub password: Option<String>,
}
impl Config {
pub fn build(filename: &str) -> Result<Self, Box<dyn Error>> {
debug!("Loading config: {filename}");
let file = fs::read_to_string(filename)?;
let mut config: Self = toml::from_str(&file)?;
config.mqtt.password = Some(std::env::var("MQTT_PASSWORD").or(config.mqtt.password.ok_or("MQTT password needs to be set in either config or the environment!"))?);
Ok(config)
}
}