axum/axum-macros/tests/from_request/pass/state_via.rs
David Pedersen c3f3db79ec
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
2022-09-23 23:50:50 +02:00

28 lines
663 B
Rust

use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
use axum_macros::FromRequest;
fn main() {
let _: Router<AppState> = Router::with_state(AppState::default())
.route("/b", get(|_: (), _: AppState| async {}))
.route("/c", get(|_: (), _: InnerState| async {}));
}
#[derive(Clone, Default, FromRequest)]
#[from_request(via(State), state(AppState))]
struct AppState {
inner: InnerState,
}
#[derive(Clone, Default, FromRequest)]
#[from_request(via(State), state(AppState))]
struct InnerState {}
impl FromRef<AppState> for InnerState {
fn from_ref(input: &AppState) -> Self {
input.inner.clone()
}
}