Crate axum_conf

Crate axum_conf 

Source
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:

§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

FeatureDescriptionDefault
Health probes/live and /ready endpointsEnabled
Prometheus metricsRequest counts, latencies at /metricsEnabled
Request loggingStructured logs with UUIDv7 correlation IDsEnabled
Rate limitingPer-IP request throttling100 req/sec
Security headersX-Frame-Options, X-Content-Type-OptionsEnabled
Panic recoveryCatches panics, returns 500, keeps runningEnabled
Graceful shutdownHandles SIGTERM, drains connections30s timeout
Compressiongzip, brotli, deflate, zstdAvailable

§Cargo Features

FeatureDescription
postgresPostgreSQL connection pooling (enables rustls)
keycloakOIDC/JWT authentication (enables session)
sessionCookie-based session management
opentelemetryDistributed tracing with OTLP export
basic-authHTTP Basic Auth and API key authentication
rustlsTLS support

§Module Organization

ModuleDescription
configConfiguration loading and validation (Config)
fluentRouter builder and middleware setup (FluentRouter)
errorError types and handling (Error)
utilsUtilities (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§

pub use config::*;
pub use fluent::*;

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.
ErrorResponse
Structured error response with error code and details.
RequestIdGenerator
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§

ErrorKind
The kind of error that occurred.

Functions§

replace_handlebars_with_env
Replaces handlebars-style placeholders with environment variable values.

Type Aliases§

Result