Struct actix_web::web::Data

source ·
pub struct Data<T: ?Sized>(/* private fields */);
Expand description

Application data wrapper and extractor.

§Setting Data

Data is set using the app_data methods on App, Scope, and Resource. If data is wrapped in this Data type for those calls, it can be used as an extractor.

Note that Data should be constructed outside the HttpServer::new closure if shared, potentially mutable state is desired. Data is cheap to clone; internally, it uses an Arc.

See also App::app_data, Scope::app_data, and Resource::app_data.

§Extracting Data

Since the Actix Web router layers application data, the returned object will reference the “closest” instance of the type. For example, if an App stores a u32, a nested Scope also stores a u32, and the delegated request handler falls within that Scope, then extracting a web::Data<u32> for that handler will return the Scope’s instance. However, using the same router set up and a request that does not get captured by the Scope, web::<Data<u32>> would return the App’s instance.

If route data is not set for a handler, using Data<T> extractor would cause a 500 Internal Server Error response.

See also HttpRequest::app_data and ServiceRequest::app_data.

§Unsized Data

For types that are unsized, most commonly dyn T, Data can wrap these types by first constructing an Arc<dyn T> and using the From implementation to convert it.

let displayable_arc: Arc<dyn Display> = Arc::new(42usize);
let displayable_data: Data<dyn Display> = Data::from(displayable_arc);

§Examples

use std::sync::Mutex;
use actix_web::{App, HttpRequest, HttpResponse, Responder, web::{self, Data}};

struct MyData {
    counter: usize,
}

/// Use the `Data<T>` extractor to access data in a handler.
async fn index(data: Data<Mutex<MyData>>) -> impl Responder {
    let mut my_data = data.lock().unwrap();
    my_data.counter += 1;
    HttpResponse::Ok()
}

/// Alternatively, use the `HttpRequest::app_data` method to access data in a handler.
async fn index_alt(req: HttpRequest) -> impl Responder {
    let data = req.app_data::<Data<Mutex<MyData>>>().unwrap();
    let mut my_data = data.lock().unwrap();
    my_data.counter += 1;
    HttpResponse::Ok()
}

let data = Data::new(Mutex::new(MyData { counter: 0 }));

let app = App::new()
    // Store `MyData` in application storage.
    .app_data(Data::clone(&data))
    .route("/index.html", web::get().to(index))
    .route("/index-alt.html", web::get().to(index_alt));

Implementations§

source§

impl<T> Data<T>

source

pub fn new(state: T) -> Data<T>

Create new Data instance.

source§

impl<T: ?Sized> Data<T>

source

pub fn get_ref(&self) -> &T

Returns reference to inner T.

source

pub fn into_inner(self) -> Arc<T>

Unwraps to the internal Arc<T>

Trait Implementations§

source§

impl<T: ?Sized> Clone for Data<T>

source§

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

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
source§

impl<T: Debug + ?Sized> Debug for Data<T>

source§

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

Formats the value using the given formatter. Read more
source§

impl<T: Default> Default for Data<T>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<T: ?Sized> Deref for Data<T>

§

type Target = Arc<T>

The resulting type after dereferencing.
source§

fn deref(&self) -> &Arc<T>

Dereferences the value.
source§

impl<'de, T> Deserialize<'de> for Data<T>
where T: Deserialize<'de>,

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl<T: ?Sized> From<Arc<T>> for Data<T>

source§

fn from(arc: Arc<T>) -> Self

Converts to this type from the input type.
source§

impl<T: ?Sized + 'static> FromRequest for Data<T>

§

type Error = Error

The associated error which can be returned.
§

type Future = Ready<Result<Data<T>, Error>>

Future that resolves to a Self. Read more
source§

fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future

Create a Self from request parts asynchronously.
source§

fn extract(req: &HttpRequest) -> Self::Future

Create a Self from request head asynchronously. Read more
source§

impl<T> Serialize for Data<T>
where T: Serialize,

source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Data<T>
where T: ?Sized,

§

impl<T> RefUnwindSafe for Data<T>
where T: RefUnwindSafe + ?Sized,

§

impl<T> Send for Data<T>
where T: Sync + Send + ?Sized,

§

impl<T> Sync for Data<T>
where T: Sync + Send + ?Sized,

§

impl<T> Unpin for Data<T>
where T: ?Sized,

§

impl<T> UnwindSafe for Data<T>
where T: RefUnwindSafe + ?Sized,

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<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Same for T

§

type Output = T

Should always be Self
source§

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

§

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<T, U> TryFrom<U> for T
where U: Into<T>,

§

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>,

§

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<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
source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

source§

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

source§

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