refactor configs into a crate

This commit is contained in:
GW_MC
2025-11-27 18:59:40 +08:00
parent bb622df89b
commit 537737b1cc
8 changed files with 249 additions and 221 deletions

View File

@@ -0,0 +1,56 @@
use std::net::IpAddr;
use config::{Config, ConfigError};
use tracing::warn;
use super::{
FromConfig,
key::{SERVER_ADDRESS_KEY, SERVER_PORT_KEY},
};
#[derive(Debug, Clone)]
pub struct ServerSettings {
pub address: IpAddr,
pub port: u16,
}
impl FromConfig for ServerSettings {
fn from_config(_config: &Config) -> Result<Self, String> {
Ok(ServerSettings {
address: _config
.get_string(SERVER_ADDRESS_KEY)
.unwrap_or_else(|err| {
const DEFAULT_ADDRESS: &str = "0.0.0.0";
match err {
ConfigError::NotFound(_) => {}
_ => {
warn!(
"Failed to read {} from configuration, defaulting to {}. Error: {}",
SERVER_ADDRESS_KEY, DEFAULT_ADDRESS, err
);
}
};
DEFAULT_ADDRESS.to_string()
})
.parse()
.map_err(|e| format!("Invalid {} in configuration: {}", SERVER_ADDRESS_KEY, e))?,
port: _config.get_int(SERVER_PORT_KEY).unwrap_or_else(|err| {
const DEFAULT_PORT: i64 = 8080;
warn!(
"{} not set or invalid in configuration, defaulting to {}. Error: {}",
SERVER_PORT_KEY, DEFAULT_PORT, err
);
DEFAULT_PORT
}) as u16,
})
}
fn validate(&self) -> Result<(), String> {
#[allow(clippy::absurd_extreme_comparisons, unused_comparisons)]
if self.port == 0 || self.port > 65535 {
return Err("Server port must be between 1 and 65535".into());
}
Ok(())
}
}