Skip to main content

Extension

Struct Extension 

Source
pub struct Extension<T>(pub T);
Expand description

Extractor and response for extensions.

ยงAs extractor

This is commonly used to share state across handlers.

use axum::{
    Router,
    Extension,
    routing::get,
};
use std::sync::Arc;

// Some shared state used throughout our application
struct State {
    // ...
}

async fn handler(state: Extension<Arc<State>>) {
    // ...
}

let state = Arc::new(State { /* ... */ });

let app = Router::new().route("/", get(handler))
    // Add middleware that inserts the state into all incoming request's
    // extensions.
    .layer(Extension(state));

If the extension is missing it will reject the request with a 500 Internal Server Error response. Alternatively, you can use Option<Extension<T>> to make the extension extractor optional.

ยงAs response

Response extensions can be used to share state with middleware.

use axum::{
    Extension,
    response::IntoResponse,
};

async fn handler() -> (Extension<Foo>, &'static str) {
    (
        Extension(Foo("foo")),
        "Hello, World!"
    )
}

#[derive(Clone)]
struct Foo(&'static str);

Tuple Fieldsยง

ยง0: T

Trait Implementationsยง

Sourceยง

impl<T> Clone for Extension<T>
where T: Clone,

Sourceยง

fn clone(&self) -> Extension<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) ยท Sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Sourceยง

impl<T> Copy for Extension<T>
where T: Copy,

Sourceยง

impl<T> Debug for Extension<T>
where T: Debug,

Sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Sourceยง

impl<T> Default for Extension<T>
where T: Default,

Sourceยง

fn default() -> Extension<T>

Returns the โ€œdefault valueโ€ for a type. Read more
Sourceยง

impl<T> Deref for Extension<T>

Sourceยง

type Target = T

The resulting type after dereferencing.
Sourceยง

fn deref(&self) -> &<Extension<T> as Deref>::Target

Dereferences the value.
Sourceยง

impl<T> DerefMut for Extension<T>

Sourceยง

fn deref_mut(&mut self) -> &mut <Extension<T> as Deref>::Target

Mutably dereferences the value.
Sourceยง

impl<T, S> FromRequestParts<S> for Extension<T>
where T: Clone + Send + Sync + 'static, S: Send + Sync,

Sourceยง

type Rejection = ExtensionRejection

If the extractor fails itโ€™ll use this โ€œrejectionโ€ type. A rejection is a kind of error that can be converted into a response.
Sourceยง

async fn from_request_parts( req: &mut Parts, _state: &S, ) -> Result<Extension<T>, <Extension<T> as FromRequestParts<S>>::Rejection>

Perform the extraction.
Sourceยง

impl<T> IntoResponse for Extension<T>
where T: Clone + Send + Sync + 'static,

Sourceยง

fn into_response(self) -> Response<Body>

Create a response.
Sourceยง

impl<T> IntoResponseParts for Extension<T>
where T: Clone + Send + Sync + 'static,

Sourceยง

type Error = Infallible

The type returned in the event of an error. Read more
Sourceยง

fn into_response_parts( self, res: ResponseParts, ) -> Result<ResponseParts, <Extension<T> as IntoResponseParts>::Error>

Set parts of the response
Sourceยง

impl<S, T> Layer<S> for Extension<T>
where T: Clone + Send + Sync + 'static,

Sourceยง

type Service = AddExtension<S, T>

The wrapped service
Sourceยง

fn layer(&self, inner: S) -> <Extension<T> as Layer<S>>::Service

Wrap the given service with the middleware, returning a new service that has been decorated with the middleware.
Sourceยง

impl<T, S> OptionalFromRequestParts<S> for Extension<T>
where T: Clone + Send + Sync + 'static, S: Send + Sync,

Sourceยง

type Rejection = Infallible

If the extractor fails, it will use this โ€œrejectionโ€ type. Read more
Sourceยง

async fn from_request_parts( req: &mut Parts, _state: &S, ) -> Result<Option<Extension<T>>, <Extension<T> as OptionalFromRequestParts<S>>::Rejection>

Perform the extraction.

Auto Trait Implementationsยง

ยง

impl<T> Freeze for Extension<T>
where T: Freeze,

ยง

impl<T> RefUnwindSafe for Extension<T>
where T: RefUnwindSafe,

ยง

impl<T> Send for Extension<T>
where T: Send,

ยง

impl<T> Sync for Extension<T>
where T: Sync,

ยง

impl<T> Unpin for Extension<T>
where T: Unpin,

ยง

impl<T> UnsafeUnpin for Extension<T>
where T: UnsafeUnpin,

ยง

impl<T> UnwindSafe for Extension<T>
where T: UnwindSafe,

Blanket Implementationsยง

Sourceยง

impl<T> Any for T
where T: 'static + ?Sized,

Sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Sourceยง

impl<T> Borrow<T> for T
where T: ?Sized,

Sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Sourceยง

impl<T> BorrowMut<T> for T
where T: ?Sized,

Sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Sourceยง

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Sourceยง

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Sourceยง

impl<T> CloneToUninit for T
where T: Clone,

Sourceยง

unsafe fn clone_to_uninit(&self, dest: *mut u8)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Sourceยง

impl<R> CryptoRng for R
where R: TryCryptoRng<Error = Infallible> + ?Sized,

Sourceยง

impl<T> CryptoRng for T
where T: DerefMut, <T as Deref>::Target: CryptoRng,

Sourceยง

impl<T> Formattable for T
where T: Deref, <T as Deref>::Target: Formattable,

Sourceยง

impl<T> From<T> for T

Sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

Sourceยง

impl<T> FromRef<T> for T
where T: Clone,

Sourceยง

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Sourceยง

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Sourceยง

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails itโ€™ll use this โ€œrejectionโ€ type. A rejection is a kind of error that can be converted into a response.
Sourceยง

fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

Perform the extraction.
Sourceยง

impl<T, S> Handler<IntoResponseHandler, S> for T
where T: IntoResponse + Clone + Send + Sync + 'static,

Sourceยง

type Future = Ready<Response<Body>>

The type of future calling this handler returns.
Sourceยง

fn call( self, _req: Request<Body>, _state: S, ) -> <T as Handler<IntoResponseHandler, S>>::Future

Call the handler with the given request.
Sourceยง

fn layer<L>(self, layer: L) -> Layered<L, Self, T, S>
where L: Layer<HandlerService<Self, T, S>> + Clone, <L as Layer<HandlerService<Self, T, S>>>::Service: Service<Request<Body>>,

Apply a tower::Layer to the handler. Read more
Sourceยง

fn with_state(self, state: S) -> HandlerService<Self, T, S>

Convert the handler into a Service by providing the state
Sourceยง

impl<H, T> HandlerWithoutStateExt<T> for H
where H: Handler<T, ()>,

Sourceยง

fn into_service(self) -> HandlerService<H, T, ()>

Convert the handler into a Service and no state.
Sourceยง

fn into_make_service(self) -> IntoMakeService<HandlerService<H, T, ()>>

Convert the handler into a MakeService and no state. Read more
Sourceยง

fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<HandlerService<H, T, ()>, C>

Convert the handler into a MakeService which stores information about the incoming connection and has no state. Read more
Sourceยง

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Sourceยง

impl<T> Instrument for T

Sourceยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Sourceยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Sourceยง

impl<T, U> Into<U> for T
where U: From<T>,

Sourceยง

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Sourceยง

impl<T> IntoEither for T

Sourceยง

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Sourceยง

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Sourceยง

impl<T> Parsable for T
where T: Deref, <T as Deref>::Target: Parsable,

Sourceยง

impl<T> PolicyExt for T
where T: ?Sized,

Sourceยง

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Sourceยง

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Sourceยง

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Sourceยง

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Sourceยง

type Target = T

๐Ÿ”ฌThis is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Sourceยง

impl<R> Rng for R
where R: TryRng<Error = Infallible> + ?Sized,

Sourceยง

fn next_u32(&mut self) -> u32

Return the next random u32.
Sourceยง

fn next_u64(&mut self) -> u64

Return the next random u64.
Sourceยง

fn fill_bytes(&mut self, dst: &mut [u8])

Fill dest with random data. Read more
Sourceยง

impl<R> Rng for R
where R: RngCore + ?Sized,

Sourceยง

fn random<T>(&mut self) -> T

Return a random value via the StandardUniform distribution. Read more
Sourceยง

fn random_iter<T>(self) -> Iter<StandardUniform, Self, T>

Return an iterator over random variates Read more
Sourceยง

fn random_range<T, R>(&mut self, range: R) -> T
where T: SampleUniform, R: SampleRange<T>,

Generate a random value in the given range. Read more
Sourceยง

fn random_bool(&mut self, p: f64) -> bool

Return a bool with a probability p of being true. Read more
Sourceยง

fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool

Return a bool with a probability of numerator/denominator of being true. Read more
Sourceยง

fn sample<T, D>(&mut self, distr: D) -> T
where D: Distribution<T>,

Sample a new value, using the given distribution. Read more
Sourceยง

fn sample_iter<T, D>(self, distr: D) -> Iter<D, Self, T>
where D: Distribution<T>, Self: Sized,

Create an iterator that generates values using the given distribution. Read more
Sourceยง

fn fill<T>(&mut self, dest: &mut T)
where T: Fill + ?Sized,

Fill any type implementing Fill with random data Read more
Sourceยง

fn gen<T>(&mut self) -> T

๐Ÿ‘ŽDeprecated since 0.9.0:

Renamed to random to avoid conflict with the new gen keyword in Rust 2024.

Alias for Rng::random.
Sourceยง

fn gen_range<T, R>(&mut self, range: R) -> T
where T: SampleUniform, R: SampleRange<T>,

๐Ÿ‘ŽDeprecated since 0.9.0:

Renamed to random_range

Sourceยง

fn gen_bool(&mut self, p: f64) -> bool

๐Ÿ‘ŽDeprecated since 0.9.0:

Renamed to random_bool

Alias for Rng::random_bool.
Sourceยง

fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool

๐Ÿ‘ŽDeprecated since 0.9.0:

Renamed to random_ratio

Sourceยง

impl<R> RngCore for R
where R: Rng,

Sourceยง

impl<T> RngCore for T
where T: DerefMut, <T as Deref>::Target: RngCore,

Sourceยง

fn next_u32(&mut self) -> u32

Return the next random u32. Read more
Sourceยง

fn next_u64(&mut self) -> u64

Return the next random u64. Read more
Sourceยง

fn fill_bytes(&mut self, dst: &mut [u8])

Fill dest with random data. Read more
Sourceยง

impl<R> RngExt for R
where R: Rng + ?Sized,

Sourceยง

fn random<T>(&mut self) -> T

Return a random value via the StandardUniform distribution. Read more
Sourceยง

fn random_iter<T>(self) -> Iter<StandardUniform, Self, T>

Return an iterator over random variates Read more
Sourceยง

fn random_range<T, R>(&mut self, range: R) -> T
where T: SampleUniform, R: SampleRange<T>,

Generate a random value in the given range. Read more
Sourceยง

fn random_bool(&mut self, p: f64) -> bool

Return a bool with a probability p of being true. Read more
Sourceยง

fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool

Return a bool with a probability of numerator/denominator of being true. Read more
Sourceยง

fn sample<T, D>(&mut self, distr: D) -> T
where D: Distribution<T>,

Sample a new value, using the given distribution. Read more
Sourceยง

fn sample_iter<T, D>(self, distr: D) -> Iter<D, Self, T>
where D: Distribution<T>, Self: Sized,

Create an iterator that generates values using the given distribution. Read more
Sourceยง

fn fill<T>(&mut self, dest: &mut [T])
where T: Fill,

Fill any type implementing Fill with random data Read more
Sourceยง

impl<T> Same for T

Sourceยง

type Output = T

Should always be Self
Sourceยง

impl<T> ToOwned for T
where T: Clone,

Sourceยง

type Owned = T

The resulting type after obtaining ownership.
Sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Sourceยง

impl<R> TryCryptoRng for R
where R: DerefMut, <R as Deref>::Target: TryCryptoRng,

Sourceยง

impl<R> TryCryptoRng for R
where R: CryptoRng + ?Sized,

Sourceยง

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
Sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Sourceยง

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Sourceยง

impl<R> TryRng for R
where R: DerefMut, <R as Deref>::Target: TryRng,

Sourceยง

type Error = <<R as Deref>::Target as TryRng>::Error

The type returned in the event of a RNG error. Read more
Sourceยง

fn try_next_u32(&mut self) -> Result<u32, <R as TryRng>::Error>

Return the next random u32.
Sourceยง

fn try_next_u64(&mut self) -> Result<u64, <R as TryRng>::Error>

Return the next random u64.
Sourceยง

fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), <R as TryRng>::Error>

Fill dst entirely with random data.
Sourceยง

impl<R> TryRngCore for R
where R: TryRng,

Sourceยง

type Error = <R as TryRng>::Error

๐Ÿ‘ŽDeprecated since 0.10.0:

use TryRng instead

Error type.
Sourceยง

impl<R> TryRngCore for R
where R: RngCore + ?Sized,

Sourceยง

type Error = Infallible

The type returned in the event of a RNG error.
Sourceยง

fn try_next_u32(&mut self) -> Result<u32, <R as TryRngCore>::Error>

Return the next random u32.
Sourceยง

fn try_next_u64(&mut self) -> Result<u64, <R as TryRngCore>::Error>

Return the next random u64.
Sourceยง

fn try_fill_bytes( &mut self, dst: &mut [u8], ) -> Result<(), <R as TryRngCore>::Error>

Fill dest entirely with random data.
Sourceยง

fn unwrap_err(self) -> UnwrapErr<Self>
where Self: Sized,

Wrap RNG with the UnwrapErr wrapper.
Sourceยง

fn unwrap_mut(&mut self) -> UnwrapMut<'_, Self>

Wrap RNG with the UnwrapMut wrapper.
Sourceยง

fn read_adapter(&mut self) -> RngReadAdapter<'_, Self>
where Self: Sized,

Convert an RngCore to a RngReadAdapter.
Sourceยง

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Sourceยง

fn vzip(self) -> V

Sourceยง

impl<T> WithSubscriber for T

Sourceยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Sourceยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more