Struct actix_web::web::Data

source ·
pub struct Data<T: ?Sized>(_);
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()
}

/// Alteratively, 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: ?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<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: ?Sized> RefUnwindSafe for Data<T>where T: RefUnwindSafe,

§

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

§

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

§

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

§

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

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · 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 Twhere U: From<T>,

const: unstable · 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<T> for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for Twhere 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 Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
§

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

§

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> Formattable for Twhere T: Deref, <T as Deref>::Target: Formattable,

source§

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