Struct State
struct State<S>(2357)
Extractor for state.
See "Accessing state in middleware" for how to access state in middleware.
State is global and used in every request a router with state receives.
For accessing data derived from requests, such as authorization data, see Extension.
With Router
use ;
// the application state
//
// here you can put configuration, database connection pools, or whatever
// state you need
let state = AppState ;
// create a `Router` that holds our state
let app = new
.route
// provide the state so the router can access it
.with_state;
async
# let _: Router = app;
Note that State is an extractor, so be sure to put it before any body
extractors, see "the order of extractors".
Combining stateful routers
Multiple Routers can be combined with Router::nest or Router::merge
When combining Routers with one of these methods, the Routers must have
the same state type. Generally, this can be inferred automatically:
use ;
let state = AppState ;
// create a `Router` that will be nested within another
let api = new
.route;
let app = new
.nest
.with_state;
async
# let _: Router = app;
However, if you are composing Routers that are defined in separate scopes,
you may need to annotate the State type explicitly:
use ;
// the inner Router must specify its state type to compose with the
// outer router
async
# let _: Router = make_app;
In short, a Router's generic state type defaults to ()
(no state) unless Router::with_state is called or the value
of the generic type is given explicitly.
With MethodRouter
use ;
let state = AppState ;
let method_router_with_state = get
// provide the state so the handler can access it
.with_state;
# let _: MethodRouter = method_router_with_state;
async
With Handler
use ;
let state = AppState ;
async
// provide the state so the handler can access it
let handler_with_state = handler.with_state;
# async ;
Substates
State only allows a single state type but you can use FromRef to extract "substates":
use ;
// the application state
// the api specific state
// support converting an `AppState` in an `ApiState`
let state = AppState ;
let app = new
.route
.route
.with_state;
async
async
# let _: Router = app;
For convenience FromRef can also be derived using #[derive(FromRef)].
For library authors
If you're writing a library that has an extractor that needs state, this is the recommended way to do it:
use ;
use Parts;
use Infallible;
// the extractor your library provides
;
// the state your library needs
Shared mutable state
As state is global within a Router you can't directly get a mutable reference to
the state.
The most basic solution is to use an Arc<Mutex<_>>. Which kind of mutex you need depends on
your use case. See the tokio docs for more details.
Note that holding a locked std::sync::Mutex across .await points will result in !Send
futures which are incompatible with axum. If you need to hold a mutex across .await points,
consider using a tokio::sync::Mutex instead.
Example
use ;
use ;
async
let state = AppState ;
let app = new
.route
.with_state;
# let _: Router = app;
Implementations
impl<OuterState, InnerState> FromRequestParts for State<InnerState>
async fn from_request_parts(_parts: &mut Parts, state: &OuterState) -> Result<Self, <Self as >::Rejection>
impl<P, T> Receiver for State<S>
impl<R> Rng for State<S>
impl<R> TryCryptoRng for State<S>
impl<R> TryRngCore for State<S>
fn try_next_u32(self: &mut Self) -> Result<u32, <R as TryRngCore>::Error>fn try_next_u64(self: &mut Self) -> Result<u64, <R as TryRngCore>::Error>fn try_fill_bytes(self: &mut Self, dst: &mut [u8]) -> Result<(), <R as TryRngCore>::Error>
impl<S> Deref for State<S>
fn deref(self: &Self) -> &<Self as >::Target
impl<S> DerefMut for State<S>
fn deref_mut(self: &mut Self) -> &mut <Self as >::Target
impl<S> Freeze for State<S>
impl<S> RefUnwindSafe for State<S>
impl<S> Send for State<S>
impl<S> Sync for State<S>
impl<S> Unpin for State<S>
impl<S> UnsafeUnpin for State<S>
impl<S> UnwindSafe for State<S>
impl<S, T> FromRequest for State<S>
fn from_request(req: Request<Body>, state: &S) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>
impl<S: $crate::clone::Clone> Clone for State<S>
fn clone(self: &Self) -> State<S>
impl<S: $crate::default::Default> Default for State<S>
fn default() -> State<S>
impl<S: $crate::fmt::Debug> Debug for State<S>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<S: $crate::marker::Copy> Copy for State<S>
impl<T> Any for State<S>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for State<S>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for State<S>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for State<S>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> CryptoRng for State<S>
impl<T> From for State<S>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> FromRef for State<S>
fn from_ref(input: &T) -> T
impl<T> Instrument for State<S>
impl<T> RngCore for State<S>
fn next_u32(self: &mut Self) -> u32fn next_u64(self: &mut Self) -> u64fn fill_bytes(self: &mut Self, dst: &mut [u8])
impl<T> Same for State<S>
impl<T> ToOwned for State<S>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T> WithSubscriber for State<S>
impl<T, U> Into for State<S>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for State<S>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for State<S>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<V, T> VZip for State<S>
fn vzip(self: Self) -> V