Derive Macro axum::extract::FromRef

source ·
#[derive(FromRef)]
{
    // Attributes available to this derive:
    #[from_ref]
}
Available on crate feature macros only.
Expand description

Derive an implementation of FromRef for each field in a struct.

§Example

use axum::{
    Router,
    routing::get,
    extract::{State, FromRef},
};

// This will implement `FromRef` for each field in the struct.
#[derive(FromRef, Clone)]
struct AppState {
    auth_token: AuthToken,
    database_pool: DatabasePool,
    // fields can also be skipped
    #[from_ref(skip)]
    api_token: String,
}

// So those types can be extracted via `State`
async fn handler(State(auth_token): State<AuthToken>) {}

async fn other_handler(State(database_pool): State<DatabasePool>) {}

let state = AppState {
    auth_token,
    database_pool,
    api_token: "secret".to_owned(),
};

let app = Router::new()
    .route("/", get(handler).post(other_handler))
    .with_state(state);