Struct State
pub struct State<S>(pub S);
Extractor for state.
See "Sharing state with handlers" for an overview of all approaches to
sharing state, including when to use Arc, how FromRef substates work, and what the
Router<S> type parameter means.
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;
Fields
0: S
Trait Implementations
impl<OuterState, InnerState> FromRequestParts<OuterState> for State<InnerState>
where
InnerState: FromRef<OuterState>,
OuterState: Send + Sync,
type Rejection = never;async fn from_request_parts(_parts: &mut Parts, state: &OuterState) -> Result<Self, Self::Rejection>
impl<S> Deref for State<S>
type Target = S;fn deref(&self) -> &Self::Target
impl<S> DerefMut for State<S>
fn deref_mut(&mut self) -> &mut Self::Target
impl<S: Clone> Clone for State<S>
fn clone(&self) -> Self
impl<S: Copy> Copy for State<S>
impl<S: Debug> Debug for State<S>
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl<S: Default> Default for State<S>
fn default() -> Self
Auto Trait Implementations
impl<S> Freeze for State<S>
where
S: Freeze,
impl<S> RefUnwindSafe for State<S>
where
S: RefUnwindSafe,
impl<S> Send for State<S>
where
S: Send,
impl<S> Sync for State<S>
where
S: Sync,
impl<S> Unpin for State<S>
where
S: Unpin,
impl<S> UnsafeUnpin for State<S>
where
S: UnsafeUnpin,
impl<S> UnwindSafe for State<S>
where
S: UnwindSafe,
Blanket Implementations
impl<P, T> Receiver for State<S>
where
P: Deref<Target = T> + ?Sized,
T: ?Sized,
type Target = T;
impl<R> Rng for State<S>
where
R: RngCore + ?Sized,
impl<R> TryCryptoRng for State<S>
where
R: CryptoRng + ?Sized,
impl<R> TryRngCore for State<S>
where
R: RngCore + ?Sized,
type Error = never;fn try_next_u32(&mut self) -> Result<u32, <R as TryRngCore>::Error>fn try_next_u64(&mut self) -> Result<u64, <R as TryRngCore>::Error>fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), <R as TryRngCore>::Error>
impl<S, T> FromRequest<S, ViaParts> for State<S>
where
S: Send + Sync,
T: FromRequestParts<S>,
type Rejection = <T as FromRequestParts<S>>::Rejection;fn from_request(req: Request<Body>, state: &S) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for State<S>
where
ST: ?Sized,
DT: ?Sized,
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for State<S>
where
ST: ?Sized,
DT: ?Sized,
impl<T> Any for State<S>
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for State<S>
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for State<S>
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> CloneToUninit for State<S>
where
T: Clone,
unsafe fn clone_to_uninit(&self, dest: *mut u8)
impl<T> CryptoRng for State<S>
where
T: DerefMut,
<T as Deref>::Target: CryptoRng,
impl<T> From<T> for State<S>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> FromRef<T> for State<S>
where
T: Clone,
fn from_ref(input: &T) -> T
impl<T> Instrument for State<S>
impl<T> Read<Exclusive, BecauseExclusive> for State<S>
where
T: ?Sized,
impl<T> RngCore for State<S>
where
T: DerefMut,
<T as Deref>::Target: RngCore,
fn next_u32(&mut self) -> u32fn next_u64(&mut self) -> u64fn fill_bytes(&mut self, dst: &mut [u8])
impl<T> Same for State<S>
type Output = T;
impl<T> ToOwned for State<S>
where
T: Clone,
type Owned = T;fn to_owned(&self) -> Tfn clone_into(&self, target: &mut T)
impl<T> WithSubscriber for State<S>
impl<T, U> Into<U> for State<S>
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for State<S>
where
U: Into<T>,
type Error = never;fn try_from(value: U) -> Result<T, never>
impl<T, U> TryInto<U> for State<S>
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
impl<V, T> VZip<V> for State<S>
where
V: MultiLane<T>,
fn vzip(self) -> V