feat: using config crate
Some checks failed
Rust / build_and_test (push) Failing after 34s

This commit is contained in:
Lukas Wölfer
2026-04-10 23:47:13 +02:00
parent b6f03f9efb
commit 5b9ab3f47d
4 changed files with 256 additions and 117 deletions

View File

@@ -1,5 +1,4 @@
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -36,54 +35,57 @@ pub struct SessionConfig {
}
impl Config {
/// Load configuration from a TOML file
/// Falls back to environment variables if file doesn't exist
/// Load configuration from a TOML file and environment variables
/// config-rs merges file config with environment variables automatically
pub fn load(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
let mut builder = config::Config::builder();
// Add default values first
let defaults = Self::defaults();
builder = builder.add_source(
config::Config::try_from(&defaults)
.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?,
);
// Load from file if it exists
if Path::new(path).exists() {
let content = fs::read_to_string(path)?;
let config: Config = toml::from_str(&content)?;
Ok(config)
} else {
// Fall back to environment variables
Ok(Config::from_env())
builder = builder.add_source(config::File::with_name(path).required(false));
}
// Override with environment variables
// Environment variables should be prefixed with the app name and use __ for nesting
// e.g., WEIGHT_TRACKER_OIDC__CLIENT_ID for oidc.client_id
builder = builder.add_source(
config::Environment::with_prefix("WEIGHT_TRACKER")
.try_parsing(true)
.separator("__"),
);
let config = builder.build()?;
let result: Config = config.try_deserialize()?;
Ok(result)
}
/// Load configuration from environment variables
pub fn from_env() -> Self {
let client_id =
std::env::var("OIDC_CLIENT_ID").unwrap_or_else(|_| "your_client_id".to_string());
let client_secret = std::env::var("OIDC_CLIENT_SECRET")
.unwrap_or_else(|_| "your_client_secret".to_string());
let auth_url = std::env::var("OIDC_AUTH_URL")
.unwrap_or_else(|_| "https://your-provider.com/auth".to_string());
let token_url = std::env::var("OIDC_TOKEN_URL")
.unwrap_or_else(|_| "https://your-provider.com/token".to_string());
let redirect_url = std::env::var("OIDC_REDIRECT_URL")
.unwrap_or_else(|_| "http://localhost:3000/auth/callback".to_string());
let host = std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = std::env::var("SERVER_PORT")
.unwrap_or_else(|_| "3000".to_string())
.parse()
.unwrap_or(3000);
let database_url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "sqlite:weight_tracker.db".to_string());
let session_secret = std::env::var("SESSION_SECRET").unwrap_or_else(|_| {
"your_secret_key_that_is_long_enough_so_the_library_does_not_complain".to_string()
});
/// Get default configuration values
fn defaults() -> Self {
Config {
oidc: OidcConfig {
client_id,
client_secret,
auth_url,
token_url,
redirect_url,
client_id: "your_client_id".to_string(),
client_secret: "your_client_secret".to_string(),
auth_url: "https://your-provider.com/auth".to_string(),
token_url: "https://your-provider.com/token".to_string(),
redirect_url: "http://localhost:3000/auth/callback".to_string(),
},
server: ServerConfig {
host: "127.0.0.1".to_string(),
port: 3000,
},
database: DatabaseConfig {
url: "sqlite:weight_tracker.db".to_string(),
},
server: ServerConfig { host, port },
database: DatabaseConfig { url: database_url },
session: SessionConfig {
secret: session_secret,
secret: "your_secret_key_that_is_long_enough_so_the_library_does_not_complain"
.to_string(),
},
}
}

View File

@@ -5,9 +5,11 @@ use weight_tracker::{AppState, create_app, config::Config};
#[tokio::main]
async fn main() {
// Load configuration from config.toml or environment variables
let config = Config::load("config.toml").unwrap_or_else(|_| {
println!("config.toml not found, using environment variables");
Config::from_env()
// config-rs automatically merges file + environment + defaults
let config = Config::load("config.toml").unwrap_or_else(|e| {
eprintln!("Failed to load configuration: {}", e);
eprintln!("Using default values. Set environment variables prefixed with WEIGHT_TRACKER_ to override.");
std::process::exit(1);
});
// Set up database