mirror of
https://github.com/tokio-rs/axum.git
synced 2026-09-08 00:00:24 +02:00
Support State with #[derive(FromRequest[Parts])] (#1391)
* 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
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
use axum::{
|
||||
extract::{State, FromRef},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use axum_macros::FromRequest;
|
||||
|
||||
fn main() {
|
||||
let _: Router<AppState> = Router::with_state(AppState::default())
|
||||
.route("/a", get(|_: AppState| async {}))
|
||||
.route("/b", get(|_: InnerState| async {}));
|
||||
}
|
||||
|
||||
#[derive(Clone, FromRequest)]
|
||||
#[from_request(via(State))]
|
||||
enum AppState {
|
||||
One,
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
fn default() -> AppState {
|
||||
Self::One
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FromRequest)]
|
||||
#[from_request(via(State), state(AppState))]
|
||||
enum InnerState {}
|
||||
|
||||
impl FromRef<AppState> for InnerState {
|
||||
fn from_ref(_: &AppState) -> Self {
|
||||
todo!(":shrug:")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user