footing 0.1.21

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

use axum::{
    Json,
    http::{HeaderValue, header},
    middleware,
    response::Response,
};
use footing::http::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 = OpenApiDocs::new(document, "/docs", ui)
        .into_router()?
        .layer(middleware::map_response(
            |mut response: Response| async move {
                // ReDoc generates styles at runtime and uses a Blob worker for search.
                response.headers_mut().insert(
                    header::CONTENT_SECURITY_POLICY,
                    HeaderValue::from_static(concat!(
                        "default-src 'none'; script-src 'self'; connect-src 'self'; ",
                        "style-src 'self' 'unsafe-inline'; img-src 'self' data:; ",
                        "font-src 'self'; worker-src 'self' blob:; base-uri 'none'; ",
                        "object-src 'none'; frame-ancestors 'none'",
                    )),
                );
                response
            },
        ));
    // Apply application-specific access control to `docs` before merging it.
    let app = 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"),
    }
}