mirror of
https://github.com/tokio-rs/axum.git
synced 2024-11-23 07:39:25 +01:00
c3f3db79ec
* Support `State` with `#[derive(FromRequest[Parts])]` Fixes https://github.com/tokio-rs/axum/issues/1314 This makes it possible to extract things via `State` in `#[derive(FromRequet)]`: ```rust struct Foo { state: State<AppState>, } ``` The state can also be inferred in a lot of cases so you only need to write: ```rust struct Foo { // since we're using `State<AppState>` we know the state has to be // `AppState` state: State<AppState>, } ``` Same for ```rust struct Foo { #[from_request(via(State))] state: AppState, } ``` And ```rust struct AppState {} ``` I think I've covered all the edge cases but there are (unsurprisingly) a few. * make sure things can be combined with other extractors * main functions in ui tests don't need to be async * Add test for multiple identicaly state types * Add failing test for multiple states
44 lines
805 B
Rust
44 lines
805 B
Rust
use axum_macros::FromRequest;
|
|
use axum::{
|
|
extract::{FromRef, State},
|
|
Router,
|
|
routing::get,
|
|
};
|
|
|
|
fn main() {
|
|
let _: Router<AppState> = Router::with_state(AppState::default())
|
|
.route("/b", get(|_: Extractor| async {}));
|
|
}
|
|
|
|
#[derive(FromRequest)]
|
|
#[from_request(state(AppState))]
|
|
struct Extractor {
|
|
app_state: State<AppState>,
|
|
one: State<One>,
|
|
two: State<Two>,
|
|
other_extractor: String,
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct AppState {
|
|
one: One,
|
|
two: Two,
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct One {}
|
|
|
|
impl FromRef<AppState> for One {
|
|
fn from_ref(input: &AppState) -> Self {
|
|
input.one.clone()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct Two {}
|
|
|
|
impl FromRef<AppState> for Two {
|
|
fn from_ref(input: &AppState) -> Self {
|
|
input.two.clone()
|
|
}
|
|
}
|