full with cli options and config support and all endpoints for crud

operations
This commit is contained in:
wt committed 2025-11-11 03:33:28 +07:00
1 parent c5d44c6466
commit 6d250c9c1a
10 files changed
+483 -126

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
use clap::Parser;
use serde::Deserialize;
use std::path::PathBuf;
#[derive(Deserialize, Debug)]
struct FileConfig {
host: Option<String>,
port: Option<u16>,
log_level: Option<String>,
}
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
#[arg(short, long)]
config: Option<PathBuf>,
#[arg(short, long)]
addr: Option<String>,
#[arg(short, long)]
port: Option<u16>,
#[arg(short, long)]
log_level: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Config {
pub host: String,
pub port: u16,
pub log_level: String,
}
impl Config {
pub async fn new() -> anyhow::Result<Self> {
let cli: Cli = Cli::parse();
let file_config: FileConfig = if let Some(config_path) = &cli.config {
println!("Loading config from file");
Self::load_file_config(config_path).await?
} else {
FileConfig {
host: None,
port: None,
log_level: None,
}
};
let host: String = cli
.addr
.or(file_config.host)
.unwrap_or_else(|| "0.0.0.0".to_string());
let port: u16 = cli.port.or(file_config.port).unwrap_or(8888);
let log_level: String = cli
.log_level
.or(file_config.log_level)
.unwrap_or_else(|| "info".to_string());
Ok(Config {
host,
port,
log_level,
})
}
async fn load_file_config(path: &PathBuf) -> anyhow::Result<FileConfig> {
let content = tokio::fs::read_to_string(path).await?;
let config: FileConfig = serde_json::from_str(&content)?;
Ok(config)
}
}