Expand description
§axum-conf
A batteries-included library for building production-ready web services with Axum, designed specifically for Kubernetes deployments.
Get health probes, metrics, security headers, rate limiting, and more — all configured through simple TOML.
📖 For detailed guides, see the documentation:
- Getting Started - Build your first service
- Architecture - How axum-conf works
- Configuration Reference - All options
- Troubleshooting - Common issues
§Quick Start
use axum::{Router, routing::get};
use axum_conf::{Config, Result, FluentRouter};
async fn hello() -> &'static str {
"Hello, World!"
}
#[tokio::main]
async fn main() -> Result<()> {
let config = Config::default(); // Loads from config/{RUST_ENV}.toml
config.setup_tracing();
FluentRouter::without_state(config)?
.route("/", get(hello))
.setup_middleware()
.await?
.start()
.await
}With config/dev.toml:
[http]
bind_port = 3000
max_payload_size_bytes = "1MiB"Run with RUST_ENV=dev cargo run.
§What You Get
| Feature | Description | Default |
|---|---|---|
| Health probes | /live and /ready endpoints | Enabled |
| Prometheus metrics | Request counts, latencies at /metrics | Enabled |
| Request logging | Structured logs with UUIDv7 correlation IDs | Enabled |
| Rate limiting | Per-IP request throttling | 100 req/sec |
| Security headers | X-Frame-Options, X-Content-Type-Options | Enabled |
| Panic recovery | Catches panics, returns 500, keeps running | Enabled |
| Graceful shutdown | Handles SIGTERM, drains connections | 30s timeout |
| Compression | gzip, brotli, deflate, zstd | Available |
§Cargo Features
| Feature | Description |
|---|---|
postgres | PostgreSQL connection pooling (enables rustls) |
keycloak | OIDC/JWT authentication (enables session) |
session | Cookie-based session management |
opentelemetry | Distributed tracing with OTLP export |
basic-auth | HTTP Basic Auth and API key authentication |
rustls | TLS support |
§Module Organization
| Module | Description |
|---|---|
config | Configuration loading and validation (Config) |
fluent | Router builder and middleware setup (FluentRouter) |
error | Error types and handling (Error) |
utils | Utilities (ApiVersion, Sensitive) |
§Configuration
Configuration can be loaded from TOML files, strings, or built programmatically:
use axum_conf::Config;
use std::time::Duration;
// From file (recommended for production)
let config = Config::default(); // Uses RUST_ENV
// From string (useful for tests)
let config: Config = r#"
[http]
bind_port = 3000
max_payload_size_bytes = "1KiB"
"#.parse().unwrap();
// With builder methods
let config = Config::default()
.with_bind_port(8080)
.with_compression(true)
.with_request_timeout(Duration::from_secs(30));See Configuration Reference for all options.
§Error Handling
The library uses a custom Result type. Errors convert to structured JSON responses:
{
"error_code": "DATABASE_ERROR",
"message": "Database error: connection refused"
}§Examples
§With Application State
use axum::{routing::get, extract::State};
use axum_conf::{Config, Result, FluentRouter};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Clone)]
struct AppState {
counter: Arc<AtomicU64>,
}
async fn count(State(state): State<AppState>) -> String {
let n = state.counter.fetch_add(1, Ordering::SeqCst);
format!("Count: {}", n)
}
#[tokio::main]
async fn main() -> Result<()> {
let config = Config::default();
let state = AppState { counter: Arc::new(AtomicU64::new(0)) };
FluentRouter::<AppState>::with_state(config, state)?
.route("/count", get(count))
.setup_middleware()
.await?
.start()
.await
}§With PostgreSQL
Requires the postgres feature.
[database]
url = "{{ DATABASE_URL }}"
max_pool_size = 10ⓘ
use sqlx::PgPool;
use axum::extract::State;
async fn get_users(State(pool): State<PgPool>) -> String {
let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
.fetch_one(&pool)
.await
.unwrap();
format!("Users: {}", count.0)
}See PostgreSQL Guide for details.
§Middleware Control
Enable or disable specific middleware:
[http.middleware]
exclude = ["rate-limiting", "compression"]See Middleware Overview for the full stack.
Re-exports§
Modules§
- config
- Configuration structures and utilities for wiring up the application or service.
- fluent
- FluentRouter and middleware configuration.
Structs§
- ApiVersion
- API version extracted from request headers or path.
- Error
- An error that can occur in the axum-conf library.
- Error
Response - Structured error response with error code and details.
- Request
IdGenerator - Request ID generator for distributed tracing and request correlation.
- Sensitive
- A wrapper type for sensitive data that obscures the value in debug output and securely zeros memory when dropped.
Enums§
- Error
Kind - The kind of error that occurred.
Functions§
- replace_
handlebars_ with_ env - Replaces handlebars-style placeholders with environment variable values.