|
| 1 | +use std::{ |
| 2 | + fs, |
| 3 | + path::PathBuf, |
| 4 | + time::{self, Duration}, |
| 5 | +}; |
| 6 | + |
| 7 | +use serde::Deserialize; |
| 8 | +use thiserror::Error; |
| 9 | +use toml; |
| 10 | + |
| 11 | +#[derive(Debug, Error)] |
| 12 | +pub enum ConfigError { |
| 13 | + #[error("Error while deserializing TOML: {0}")] |
| 14 | + Deserialize(#[from] toml::de::Error), |
| 15 | + |
| 16 | + #[error("Error while reading TOML config file: {0}")] |
| 17 | + Read(#[from] std::io::Error), |
| 18 | +} |
| 19 | + |
| 20 | +#[derive(Deserialize, Default)] |
| 21 | +#[serde(default)] |
| 22 | +pub struct RawConfig { |
| 23 | + interface: String, |
| 24 | + write_timeout: u64, |
| 25 | + bind_timeout: u64, |
| 26 | + read_timeout: u64, |
| 27 | +} |
| 28 | + |
| 29 | +impl RawConfig { |
| 30 | + pub fn from_file(path: PathBuf) -> Result<Self, ConfigError> { |
| 31 | + let b = match fs::read_to_string(path) { |
| 32 | + Ok(b) => b, |
| 33 | + Err(err) => return Err(ConfigError::Read(err)), |
| 34 | + }; |
| 35 | + |
| 36 | + let c: Self = match toml::from_str(&b) { |
| 37 | + Ok(c) => c, |
| 38 | + Err(err) => return Err(ConfigError::Deserialize(err)), |
| 39 | + }; |
| 40 | + |
| 41 | + Ok(c) |
| 42 | + } |
| 43 | + |
| 44 | + pub fn validate(&self) -> Result<Config, ConfigError> { |
| 45 | + Ok(Config { |
| 46 | + interface: self.interface.clone(), |
| 47 | + write_timeout: Duration::from_secs(self.write_timeout), |
| 48 | + bind_timeout: Duration::from_secs(self.bind_timeout), |
| 49 | + read_timeout: Duration::from_secs(self.read_timeout), |
| 50 | + }) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +pub struct Config { |
| 55 | + pub interface: String, |
| 56 | + pub write_timeout: time::Duration, |
| 57 | + pub bind_timeout: time::Duration, |
| 58 | + pub read_timeout: time::Duration, |
| 59 | +} |
| 60 | + |
| 61 | +impl Config { |
| 62 | + pub fn from_file(path: PathBuf) -> Result<Self, ConfigError> { |
| 63 | + let raw_config = RawConfig::from_file(path)?; |
| 64 | + raw_config.validate() |
| 65 | + } |
| 66 | +} |
0 commit comments