footing 0.6.6

Feature-gated foundations for Rust backend services
Documentation
//! Run `cargo run --example docs --features rapidoc-embedded,http-stack -- rapidoc`
//! or `cargo run --example docs --features redoc-embedded,http-stack -- redoc`.
//! Open http://127.0.0.1:3000/docs/ for the documentation page.

use axum::Json;
use footing::http::{
    HttpMiddlewareConfig, HttpMiddlewareStack,
    openapi::{DocsUi, OpenApiDocs, OpenApiRouter, route, utoipa},
};
use utoipa::OpenApi;

#[derive(serde::Serialize, utoipa::ToSchema)]
struct Item {
    id: u64,
    name: String,
}

/// List inventory items.
#[utoipa::path(get, path = "/items", tag = "Inventory", responses((status = 200, body = Vec<Item>)))]
async fn items() -> Json<Vec<Item>> {
    Json(vec![Item {
        id: 1,
        name: "Notebook".to_owned(),
    }])
}

#[derive(utoipa::OpenApi)]
#[openapi(info(title = "Inventory API", version = "1.0.0"))]
struct Api;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (app, document, _) = OpenApiRouter::new(Api::openapi())?
        .route(route!(items)?)?
        .into_parts();
    let ui = select_ui()?;
    let docs = HttpMiddlewareStack::builder(HttpMiddlewareConfig::documentation())
        .build()?
        .apply(OpenApiDocs::new(document, "/docs", ui).into_router()?);
    // Apply application-specific access control to `docs` before merging it.
    // Apply API defaults separately so their strict COOP cannot overwrite docs.
    let app = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
        .build()?
        .apply(app)
        .merge(docs);
    let listener = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 3000)).await?;
    eprintln!("API documentation: http://127.0.0.1:3000/docs/");
    axum::serve(listener, app).await?;
    Ok(())
}

fn select_ui() -> Result<DocsUi, &'static str> {
    // Prefer RapiDoc when both bundles are available; either feature works alone.
    let default = if cfg!(feature = "rapidoc-embedded") {
        "rapidoc"
    } else {
        "redoc"
    };
    match std::env::args().nth(1).as_deref().unwrap_or(default) {
        #[cfg(feature = "rapidoc-embedded")]
        "rapidoc" => Ok(DocsUi::embedded_rapidoc()),
        #[cfg(feature = "redoc-embedded")]
        "redoc" => Ok(DocsUi::embedded_redoc()),
        #[cfg(not(feature = "rapidoc-embedded"))]
        "rapidoc" => Err("enable the rapidoc-embedded feature"),
        #[cfg(not(feature = "redoc-embedded"))]
        "redoc" => Err("enable the redoc-embedded feature"),
        _ => Err("expected rapidoc or redoc"),
    }
}