RustF Configuration Guide
Complete documentation for configuration management in RustF
Overview
RustF provides a comprehensive configuration system inspired by Total.js, with a global CONF accessor that allows uniform configuration access throughout your application. Configuration can be loaded from TOML files, environment variables, or programmatically, with support for environment-specific settings and hot-reloading during development.
Key Features
- Global CONF Access - Single, uniform way to access configuration anywhere
- Dot Notation Paths - Access nested values with
"server.port"syntax - Environment Support - Development and production environments
- Multiple Sources - TOML files, environment variables, and defaults
- Type-Safe Access - Typed getters for strings, integers, booleans, and floats
- Custom Settings - Extensible with application-specific configuration
Global Configuration Access (CONF)
RustF provides a global CONF singleton that gives uniform access to configuration values using dot notation paths. This is the ONLY way to access configuration in RustF - there is no configuration access through Context or other means.
Basic Usage
#![allow(unused)]
fn main() {
use rustf::prelude::*; // CONF is included in the prelude
// Access configuration values with dot notation
let port = CONF::get_int("server.port").unwrap_or(8000);
let host = CONF::get_string("server.host").unwrap_or_else(|| "127.0.0.1".to_string());
let db_url = CONF::get_string("database.url");
// Check if a configuration path exists
if CONF::has("database.url") {
// Database is configured
}
// Get values with defaults
let timeout = CONF::get_or("server.timeout", 30);
let max_files = CONF::get_or("uploads.max_files", 5);
// Environment helpers
if CONF::is_production() {
// Enable production optimizations
}
if CONF::is_development() {
// Enable development features
}
}
CONF Methods
| Method | Description | Example |
|---|---|---|
get<T>(path) | Get typed value at path | CONF::get::<u16>("server.port") |
get_string(path) | Get string value | CONF::get_string("database.url") |
get_int(path) | Get integer value | CONF::get_int("server.port") |
get_bool(path) | Get boolean value | CONF::get_bool("server.ssl_enabled") |
get_float(path) | Get float value | CONF::get_float("custom.rate") |
get_or(path, default) | Get with default | CONF::get_or("server.port", 8000) |
has(path) | Check if path exists | CONF::has("database.url") |
env() | Get current environment | CONF::env() |
is_production() | Check if production | CONF::is_production() |
is_development() | Check if development | CONF::is_development() |
all() | Get entire config | CONF::all() |
Accessing Configuration in Different Contexts
In Controllers
#![allow(unused)]
fn main() {
use rustf::prelude::*; // CONF is included in the prelude
async fn handler(ctx: &mut Context) -> rustf::Result<()> {
// Configuration is accessed via CONF, not through ctx
let upload_dir = CONF::get_string("uploads.directory").unwrap_or_else(|| "uploads".to_string());
let max_size = CONF::get_int("uploads.max_file_size").unwrap_or(10485760);
// Use configuration values
if file.size > max_size as usize {
return ctx.throw400(Some("File too large"));
}
// Save file to upload_dir...
ctx.json(json!({ "status": "ok" }))
}
}
In Modules/Services
#![allow(unused)]
fn main() {
use rustf::prelude::*; // CONF is included in the prelude
pub struct EmailService;
impl EmailService {
pub fn send_email(&self, to: &str, subject: &str, body: &str) {
// Access custom configuration sections via CONF
// All sections (framework or custom) use the same dot notation
let smtp_host = CONF::get_string("smtp.host").unwrap_or_else(|| "localhost".to_string());
let smtp_port = CONF::get_int("smtp.port").unwrap_or(25);
let from_email = CONF::get_string("smtp.user").unwrap_or_else(|| "noreply@example.com".to_string());
// Send email using configuration...
}
}
}
In Event Handlers
#![allow(unused)]
fn main() {
use rustf::prelude::*; // CONF is included in the prelude
app.on("startup", |ctx| Box::pin(async move {
// Access configuration during startup
let db_url = CONF::get_string("database.url");
let pool_size = CONF::get_int("database.max_connections").unwrap_or(10);
if let Some(url) = db_url {
// Initialize database with configuration
initialize_database(&url, pool_size).await?;
}
Ok(())
}))
}
In Middleware
#![allow(unused)]
fn main() {
use async_trait::async_trait;
use rustf::middleware::{InboundAction, InboundMiddleware};
use rustf::prelude::*; // CONF is included in the prelude
pub struct RateLimitMiddleware;
#[async_trait]
impl InboundMiddleware for RateLimitMiddleware {
async fn process_request(&self, ctx: &mut Context) -> rustf::Result<InboundAction> {
// Access rate limit configuration
let max_requests = CONF::get_int("custom.rate_limit_max").unwrap_or(100);
let window_seconds = CONF::get_int("custom.rate_limit_window").unwrap_or(60);
// Apply rate limiting... return InboundAction::Stop to reject.
Ok(InboundAction::Continue)
}
}
}
Configuration Structure
AppConfig Schema
The main configuration structure in RustF:
#![allow(unused)]
fn main() {
pub struct AppConfig {
pub environment: Environment, // development or production
pub server: ServerConfig, // Server settings
pub views: ViewConfig, // Template engine settings
pub session: SessionConfig, // Session management
pub static_files: StaticConfig, // Static file serving
pub database: DatabaseConfig, // Database connection
pub cors: CorsConfig, // CORS settings
pub logging: LoggingConfig, // Logging configuration
pub uploads: UploadConfig, // File upload settings
pub sections: HashMap<String, toml::Value>, // User-defined configuration sections
}
}
Framework sections (above) are strongly typed for IDE support and compile-time checking. User-defined sections are stored as TOML values and can be deserialized on-demand using config.section::<T>("name").
Configuration Sections
Server Configuration
[server]
host = "127.0.0.1" # Server bind address
port = 8000 # Server port
timeout = 30 # Request timeout in seconds
ssl_enabled = false # Enable HTTPS
ssl_cert = "cert.pem" # SSL certificate path (if ssl_enabled)
ssl_key = "key.pem" # SSL private key path (if ssl_enabled)
max_connections = 1000 # Maximum concurrent connections
Views Configuration
[views]
directory = "views" # Template directory path
default_layout = "layouts/default" # Default layout template
cache_enabled = false # Enable template caching
extension = "html" # Template file extension
storage = "filesystem" # Storage method: "filesystem" or "embedded"
Session Configuration
[session]
enabled = true # Enable session middleware
cookie_name = "rustf_session" # Session cookie name
idle_timeout = 900 # Idle timeout in seconds (15 min default)
absolute_timeout = 28800 # Absolute timeout in seconds (8 hours default)
same_site = "Lax" # SameSite cookie policy
fingerprint_mode = "soft" # Fingerprint mode for session binding
exempt_routes = [] # Routes exempt from session requirement
[session.storage]
type = "memory" # Storage backend: "memory", "redis", or "database"
cleanup_interval = 300 # Cleanup interval in seconds (for memory storage)
Database Configuration
[database]
url = "postgresql://user:pass@localhost/myapp" # Database connection URL
max_connections = 10 # Connection pool size
timeout = 5000 # Connection timeout in seconds
Static Files Configuration
[static_files]
directory = "public" # Static files directory
url_prefix = "/static" # URL prefix for static files
cache_enabled = true # Enable caching headers
cache_max_age = 86400 # Cache max-age in seconds
CORS Configuration
[cors]
enabled = false # Enable CORS
allowed_origins = ["*"] # Allowed origins
allowed_methods = ["GET", "POST"] # Allowed HTTP methods
allowed_headers = ["Content-Type"] # Allowed headers
Logging Configuration
[logging]
level = "info" # Log level: debug, info, warn, error
file = "logs/app.log" # Optional log file path
Upload Configuration
[uploads]
directory = "uploads" # Upload directory
max_file_size = 10485760 # Max file size in bytes (10MB)
max_files = 5 # Max files per upload
allowed_extensions = [] # Allowed file extensions (empty = all)
blocked_extensions = ["exe", "bat", "sh", "cmd"] # Blocked extensions
create_directories = true # Auto-create upload directories
Custom Application Configuration
Any sections you define in config.toml are automatically available as configuration sections:
[app]
name = "MyApplication"
version = "1.0.0"
debug_mode = false
[payment]
stripe_key = "sk_test_xxxxx"
paypal_email = "business@example.com"
[smtp]
host = "smtp.gmail.com"
port = 587
user = "noreply@example.com"
password = "(env) SMTP_PASSWORD"
Access custom sections in Rust code using the section() method:
#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::Deserialize;
#[derive(Deserialize)]
struct AppConfig {
name: String,
version: String,
debug_mode: bool,
}
#[derive(Deserialize)]
struct PaymentConfig {
stripe_key: String,
paypal_email: String,
}
// Get typed access to custom sections
let app_cfg = config.section::<AppConfig>("app")?;
println!("App: {} v{}", app_cfg.name, app_cfg.version);
let payment = config.section::<PaymentConfig>("payment")?;
println!("Stripe key: {}", payment.stripe_key);
// Or use CONF global for uniform access
let app_name = CONF::get_string("app.name")?;
let stripe_key = CONF::get_string("payment.stripe_key")?;
}
Configuration Files
File Locations and Loading Order
Config loading follows this pipeline at startup:
- Base config (
config.toml) is loaded first — always required in release builds. - Environment is resolved from: the
RUSTF_ENVenv var → then[app] environmentfield inconfig.toml→ thendevelopmentdefault. - Overlay is merged (
config.dev.tomlorconfig.prod.toml) on top of the base using TOML-level deep merge — only the keys present in the overlay override the base. - Environment variables (
RUSTF_*prefix) override individual values after merging.
Release binary note: In release builds the binary looks for
config.tomlin the same directory as the binary itself, not in the current working directory. Placeconfig.toml,config.prod.toml,public/, andviews/next to the binary in your deployment directory.
--confignote: When using--config /path/to/config.toml, the overlay (config.prod.toml/config.dev.toml) is also automatically loaded from the same directory as the specified file.
Example config.toml
# Base configuration for all environments
[app]
environment = "development" # Controls which overlay is loaded (dev or prod)
[server]
host = "127.0.0.1"
port = 8000
timeout = 30
[views]
directory = "views"
default_layout = "layouts/default"
cache_enabled = false
extension = "html"
[session]
cookie_name = "rustf_session"
idle_timeout = 900
absolute_timeout = 28800
[database]
url = "postgresql://localhost/myapp_dev"
max_connections = 5
[static_files]
directory = "public"
url_prefix = "/static"
[uploads]
directory = "uploads"
max_file_size = 10485760
[custom]
api_endpoint = "http://localhost:3000/api"
feature_x_enabled = "false"
Environment-Specific Overrides
The overlay is loaded automatically based on the [app] environment value in config.toml. Only the keys you specify override the base — everything else is inherited.
config.prod.toml
# Production overrides — merged on top of config.toml when environment = "production"
[server]
host = "0.0.0.0"
port = 80
ssl_enabled = true
ssl_cert = "/etc/ssl/certs/app.crt"
ssl_key = "/etc/ssl/private/app.key"
max_connections = 2000
[views]
cache_enabled = true
[database]
url = "(env) DATABASE_URL" # Override with env var at runtime
max_connections = 20
[logging]
level = "warn"
file = "/var/log/rustf/app.log"
[custom]
api_endpoint = "https://api.production.com"
feature_x_enabled = "true"
Values from the Environment or Files
Any string value in config.toml (or an overlay such as config.prod.toml)
can point outside the file. The value is replaced when the configuration is
loaded:
[server]
port = "(env) PORT" # environment variable
[database]
url = "(env) DATABASE_URL"
[custom.mail]
smtp_password = "(file) /run/secrets/smtp_password" # file contents
| Reference | Value |
|---|---|
"(env) NAME" | the environment variable NAME |
"(file) PATH" | the contents of PATH, trailing newlines removed; a relative path is relative to the configuration file’s directory. The file must be a regular file of at most 1 MiB. Suited to Docker and Kubernetes secrets mounted under /run/secrets/ |
Rules:
- Missing means failure. If the variable is not set or the file cannot be
read, the application refuses to start, and the error names the key and the
variable or file. In loading errors, and in
AppConfig::sectionerrors, a resolved value is replaced by***wherever it appears quoted — which is how type errors report values, e.g. a port that does not fit — and wherever it appears unquoted if it is at least 8 characters long. A shorter value that ends up unquoted in a message (a short directory name in “directory does not exist: …”) is shown as is. - An unknown tag is an error.
"(evn) PORT"stops the application instead of loading the literal text. - Typing. A framework key takes its declared type:
"(env) PORT"becomes an integer forserver.port,"true"a boolean for a boolean key. Every other value stays a string —database.url = "(file) ..."stays a string even if the file holds123456. In your own sections nothing says whether"0042"is a number or a password, so the value stays a string and the reader decides:CONF::get::<u16>,CONF::get_or,CONF::get_int,get_float,get_boolandAppConfig::section::<T>()parse it when the requested type is a number or a boolean, andCONF::get_stringreturns it unchanged. This works for plain struct fields,Option, lists and maps; it does not reach into#[serde(flatten)]fields or untagged enums, where serde does not pass the target type down — declare those fields directly. In an overlay (config.prod.toml), a reference also takes the type of the valueconfig.tomlalready holds at that key, soretries = 3in the base can be overridden byretries = "(env) RETRIES". - Only the start of a value is a marker, in the exact form
(word)with a lowercase word."(555) 123-4567"is a plain value. A value that must literally start with a marker doubles the opening parenthesis:"((env) text"loads as"(env) text". A doubled parenthesis that is not followed by a marker ("((foo)|(bar))") is left alone. - The same resolution runs for
rustf-cli, sodbcommands see the same database URL as the application.rustf-cli validateloads the effective configuration, and checks the tags ofconfig.prod.tomlwithout resolving them (its variables and secret files are usually not on a development machine).
Templates can read the configuration. Views have access to
CONF(@{CONF.server.port},@{'%custom.key'}), and that includes values that came from(env)or(file). Never output a secret key in a template: a stray@{CONF}renders the whole configuration.
Docker example
# config.toml, shipped in the image — no secrets in it
[server]
host = "0.0.0.0"
port = "(env) PORT"
[database]
url = "(file) /run/secrets/database_url"
# docker-compose.yml
services:
app:
image: my-app
environment:
PORT: "8000"
RUSTF_ENV: production
secrets: [database_url]
secrets:
database_url:
file: ./secrets/database_url
Environment Variable Overrides
Independently of references, a fixed set of variables overrides specific keys
after the files are loaded. Only the variables below are read; other RUSTF_*
names are ignored — use "(env) NAME" for any other key.
# Environment and server
RUSTF_ENV=production # development (dev) or production (prod)
RUSTF_HOST=0.0.0.0 # required to be reachable inside a container
RUSTF_PORT=3000
RUSTF_TIMEOUT=60
RUSTF_MAX_CONNECTIONS=5000
RUSTF_PUBLIC_URL=https://example.com
RUSTF_TRUSTED_PROXIES=10.0.0.0/8
RUSTF_SSL_ENABLED=true
RUSTF_SSL_CERT=/path/to/cert
RUSTF_SSL_KEY=/path/to/key
# Database
DATABASE_URL=postgresql://user:pass@host/db # or RUSTF_DATABASE_URL
RUSTF_DB_MAX_CONNECTIONS=20
RUSTF_DB_TIMEOUT=10
# Views and static files
RUSTF_VIEWS_DIR=/app/views
RUSTF_DEFAULT_LAYOUT=layouts/main
RUSTF_VIEW_CACHE=true
RUSTF_VIEW_MINIFY=true
RUSTF_TEMPLATE_STORAGE=embedded
RUSTF_VIEW_ENGINE=totaljs
RUSTF_STATIC_DIR=/app/public
RUSTF_STATIC_PREFIX=/static
RUSTF_STATIC_CACHE=true
RUSTF_STATIC_MAX_AGE=86400
# Files
RUSTF_PRIVATE_DIR=/app/private
RUSTF_UPLOAD_DIR=uploads
RUSTF_MAX_FILE_SIZE=10485760
# CORS and logging
RUSTF_CORS_ENABLED=true
RUSTF_CORS_ORIGINS=https://a.example,https://b.example
RUSTF_CORS_METHODS=GET,POST
RUSTF_CORS_HEADERS=Content-Type,Authorization
RUSTF_LOG_LEVEL=info
RUSTF_LOG_FILE=/var/log/app.log
An exported variable applies to every application started from that shell.
When several instances run on one host, set variables per process
(RUSTF_PORT=8102 ./app --config site2/config.toml) or use references.
Loading Configuration
Application Startup
Configuration is automatically initialized during application startup:
use rustf::prelude::*;
#[rustf::auto_discover]
#[tokio::main]
async fn main() -> Result<()> {
// Configuration is loaded and CONF is initialized automatically
let app = RustF::with_args()?; // Loads config with CLI support
// Alternative loading methods:
// let app = RustF::new(); // Default config
// let app = RustF::from_file("config.toml")?; // Specific file
// let app = RustF::from_env()?; // Environment only
// let app = RustF::with_config(my_config); // Programmatic
app.start().await
}
CLI Arguments
The framework supports configuration via command-line arguments:
# Use default configuration loading
./myapp
# Specify custom config file
./myapp --config /path/to/config.toml
./myapp -c config.prod.toml
# Override views directory (if using filesystem storage)
./myapp --views /path/to/templates
Programmatic Configuration
use rustf::prelude::*;
use rustf::config::AppConfig;
#[tokio::main]
async fn main() -> rustf::Result<()> {
// Create configuration programmatically
let mut config = AppConfig::default();
config.server.port = 3000;
config.server.host = "0.0.0.0".to_string();
config.database.url = Some("postgresql://localhost/mydb".to_string());
// Use the configuration
let app = RustF::with_config(config);
app.start().await
}
Custom config sections are loaded from TOML into
AppConfig::sections(HashMap<String, toml::Value>) and read back viaconfig.section::<T>("name"), which deserializes the named section into your own struct. There is noconfig.customfield to insert into at runtime.
Environment Detection
RustF resolves the environment from these sources (in priority order):
RUSTF_ENVenvironment variable[app] environment = "production"inconfig.toml— the recommended way for per-app declaration- Default:
development
The only names accepted are development (or dev) and production (or
prod), case-insensitive. Any other value — staging, a typo — stops the
application at startup instead of silently running as development. Variables
of other tools (NODE_ENV, RAILS_ENV, …) are ignored, so a container that
sets them for something else cannot change RustF’s mode.
Everything that depends on the environment reads this one value: the
configuration overlay (config.dev.toml / config.prod.toml), production
security defaults, the session cookie’s Secure flag, detailed error pages,
DEBUG, and the environment seen by events and workers.
#![allow(unused)]
fn main() {
pub enum Environment {
Development, // Default for local development
Production, // Live production environment
}
}
The two valid string values are "production" (or "prod") and "development" (or "dev").
Environment-Specific Behavior
#![allow(unused)]
fn main() {
// Check environment in code
let env = CONF::env(); // Returns "development", "production", etc.
if CONF::is_production() {
// Production-specific code
enable_caching();
disable_debug_endpoints();
}
if CONF::is_development() {
// Development-specific code
enable_hot_reload();
show_detailed_errors();
}
}
Configuration Validation
RustF validates configuration during startup:
Automatic Validation
-
Required in Production:
- Session secret must not be default value
- SSL certificate/key paths must exist if SSL is enabled
- Database URL is recommended (warns if missing)
-
Path Validation:
- Views directory should exist (warns if missing)
- Static files directory must exist
- Upload directory is created if missing
-
Type Validation:
- Port must be valid (1-65535)
- Timeouts must be positive
- File sizes must be reasonable
Custom Validation
#![allow(unused)]
fn main() {
use rustf::prelude::*;
app.on("config.loaded", |ctx| Box::pin(async move {
// Validate custom configuration
if !CONF::has("custom.api_key") {
return Err(Error::internal("API key is required in configuration"));
}
let api_key = CONF::get_string("custom.api_key").unwrap();
if api_key.len() < 32 {
return Err(Error::internal("API key must be at least 32 characters"));
}
Ok(())
}))
}
Unified Configuration Access
RustF provides a completely unified approach to configuration access - all configuration sections (framework-defined and user-defined) can be accessed using the same patterns:
Three Ways to Access Configuration
1. Global CONF Singleton (Recommended for Runtime Access)
The CONF singleton provides dot-notation access to ANY configuration section:
#![allow(unused)]
fn main() {
use rustf::prelude::*;
// Framework sections
let port = CONF::get_int("server.port")?;
let cache_enabled = CONF::get_bool("views.cache_enabled")?;
// Custom app sections - same syntax!
let app_name = CONF::get_string("app.name")?;
let stripe_key = CONF::get_string("payment.stripe_key")?;
let smtp_port = CONF::get_int("smtp.port")?;
}
2. AppConfig.section() Method (Type-Safe Access)
For custom sections, use the section() method to get type-safe deserialized access:
#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::Deserialize;
#[derive(Deserialize)]
struct SmtpConfig {
host: String,
port: u16,
user: String,
password: String,
}
// Get the full section as a typed struct
let smtp = config.section::<SmtpConfig>("smtp")?;
println!("SMTP: {}:{}", smtp.host, smtp.port);
}
3. Templates (Automatic JSON Serialization)
Templates automatically have access to all configuration sections through the CONF global:
<!-- Framework sections -->
<meta name="viewport" content="width=device-width">
<script>
const port = @{CONF.server.port};
const cacheEnabled = @{CONF.views.cache_enabled};
</script>
<!-- Custom app sections - same access pattern -->
<h1>@{CONF.app.name} v@{CONF.app.version}</h1>
<script>
const stripeKey = '@{CONF.payment.stripe_key}';
const smtpHost = '@{CONF.smtp.host}';
</script>
Why Unified Access Matters
The unified approach eliminates cognitive overhead:
- No special buckets: Custom sections aren’t forced into
customorextramaps - One pattern: Whether accessing
server.portorapp.name, the syntax is identical - IDE support: Framework sections have typed IDE support; app sections work with runtime access
- Template consistency: Templates access all sections uniformly
- AI-friendly: One way to do things reduces confusion for human developers and AI assistants
Best Practices
1. Keep Secrets out of the Files
# config.toml
[database]
url = "(env) DATABASE_URL" # environment variable
[custom.payments]
api_key = "(file) /run/secrets/payments_key" # mounted secret
See Values from the Environment or Files.
2. Environment-Specific Files
config.toml # Base configuration — set [app] environment = "production" here
config.dev.toml # Development overrides (loaded when environment = "development")
config.prod.toml # Production overrides (loaded when environment = "production")
3. Custom Settings Organization
[custom]
# Group related settings with prefixes
smtp_host = "smtp.gmail.com"
smtp_port = "587"
smtp_user = "user@gmail.com"
smtp_password = "(env) SMTP_PASSWORD"
redis_url = "redis://localhost:6379"
redis_prefix = "myapp:"
feature_new_ui = "false"
feature_beta_api = "true"
4. Access Patterns
#![allow(unused)]
fn main() {
// ✅ Good: Use CONF for all configuration access (available in prelude)
use rustf::prelude::*;
let port = CONF::get_int("server.port").unwrap_or(8000);
let db_url = CONF::get_string("database.url");
// ❌ Bad: Don't try to access config through Context
// ctx.config() // This method no longer exists!
// ✅ Good: Check existence before accessing
if CONF::has("custom.smtp_host") {
setup_email_service();
}
// ✅ Good: Use typed getters for safety
let enabled = CONF::get_bool("custom.feature_enabled").unwrap_or(false);
let timeout = CONF::get_int("server.timeout").unwrap_or(30);
// ✅ Good: Use defaults for optional settings
let cache_size = CONF::get_or("custom.cache_size", 100);
}
5. Testing Configuration
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
use super::*;
use rustf::config::AppConfig;
#[test]
fn test_configuration_loading() {
let config = AppConfig::from_file("config.test.toml").unwrap();
// Initialize CONF for testing
CONF::init(config).unwrap();
// Test configuration values
assert_eq!(CONF::get_int("server.port"), Some(8080));
// Environment is "development" or "production" (default: "development")
assert_eq!(CONF::env(), Some("development".to_string()));
assert!(CONF::has("database.url"));
}
}
}
Migration from Context Config
If you’re migrating from an older version of RustF that had ctx.config():
Before (Old Way)
#![allow(unused)]
fn main() {
async fn handler(ctx: &mut Context) -> rustf::Result<()> {
let upload_dir = ctx.config().uploads.directory.clone();
let max_size = ctx.config().uploads.max_file_size;
// ...
}
}
After (New Way)
#![allow(unused)]
fn main() {
use rustf::prelude::*; // CONF is included in the prelude
async fn handler(ctx: &mut Context) -> rustf::Result<()> {
let upload_dir = CONF::get_string("uploads.directory").unwrap_or_else(|| "uploads".to_string());
let max_size = CONF::get_int("uploads.max_file_size").unwrap_or(10485760);
// ...
}
}
Configuration Examples
Minimal Configuration
# config.toml - Minimal configuration using defaults
[server]
port = 3000
[database]
url = "postgresql://localhost/myapp"
Full Production Configuration
# config.prod.toml — merges on top of config.toml when [app] environment = "production"
[server]
host = "0.0.0.0"
port = 443
timeout = 60
ssl_enabled = true
ssl_cert = "/etc/letsencrypt/live/example.com/fullchain.pem"
ssl_key = "/etc/letsencrypt/live/example.com/privkey.pem"
max_connections = 5000
[views]
directory = "/app/views"
default_layout = "layouts/default"
cache_enabled = true
storage = "embedded" # Use embedded templates in production
[session]
cookie_name = "app_session"
idle_timeout = 86400 # 24 hours
absolute_timeout = 604800 # 7 days
[session.storage]
type = "redis"
url = "(env) REDIS_URL"
prefix = "session:"
pool_size = 10
[database]
url = "(env) DATABASE_URL"
max_connections = 50
timeout = 10000
[static_files]
directory = "/app/public"
url_prefix = "/static"
cache_enabled = true
cache_max_age = 2592000 # 30 days
[cors]
enabled = true
allowed_origins = ["https://example.com", "https://app.example.com"]
allowed_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
allowed_headers = ["Content-Type", "Authorization", "X-Requested-With"]
[logging]
level = "info"
file = "/var/log/app/production.log"
[uploads]
directory = "/app/storage/uploads"
max_file_size = 52428800 # 50MB
max_files = 10
allowed_extensions = ["jpg", "jpeg", "png", "gif", "pdf", "doc", "docx"]
create_directories = true
[custom]
cdn_url = "https://cdn.example.com"
api_endpoint = "https://api.example.com/v1"
smtp_host = "smtp.sendgrid.net"
smtp_port = "587"
smtp_user = "apikey"
smtp_password = "(env) SENDGRID_API_KEY"
from_email = "noreply@example.com"
support_email = "support@example.com"
google_analytics_id = "UA-XXXXXXXXX-X"
stripe_public_key = "(env) STRIPE_PUBLIC_KEY"
stripe_secret_key = "(env) STRIPE_SECRET_KEY"
redis_url = "(env) REDIS_URL"
elasticsearch_url = "(env) ELASTICSEARCH_URL"
feature_new_dashboard = "true"
feature_beta_api = "false"
maintenance_mode = "false"
rate_limit_requests = "1000"
rate_limit_window = "3600"
Troubleshooting
Configuration Not Loading
#![allow(unused)]
fn main() {
// Check if CONF is initialized
if !CONF::is_initialized() {
panic!("Configuration not initialized!");
}
// Check what environment is loaded
let env = CONF::env().unwrap_or_else(|| "unknown".to_string());
println!("Running in {} environment", env);
// Debug configuration values
if let Some(config) = CONF::all() {
println!("Server port: {}", config.server.port);
println!("Database URL: {:?}", config.database.url);
}
}
Environment Variables Not Working
# Make sure to export variables
export RUSTF_PORT=3000
export DATABASE_URL="postgresql://localhost/mydb"
# Or set them when running
RUSTF_ENV=production DATABASE_URL="..." cargo run
Custom Values Not Accessible
#![allow(unused)]
fn main() {
// Custom values must be in [custom] section
// config.toml:
// [custom]
// my_value = "test"
// Access with "custom." prefix:
let value = CONF::get_string("custom.my_value"); // ✅ Correct
let value = CONF::get_string("my_value"); // ❌ Wrong
}
Summary
RustF’s configuration system provides:
✅ Single Access Point - Global CONF for uniform configuration access
✅ Dot Notation - Clean path-based access to nested values
✅ Multiple Sources - Files, environment variables, and code
✅ Environment Support - Development and production configs
✅ Type Safety - Typed getters for different value types
✅ Validation - Automatic validation for production requirements
✅ Extensibility - Custom settings for application-specific config
✅ AI-Friendly - One way to do things reduces confusion
The configuration system follows the principle of “convention over configuration” while still providing the flexibility needed for complex applications. By using the global CONF accessor exclusively, the codebase remains consistent and easy to understand for both humans and AI assistants.