logo
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

Create new Data instance.

Returns reference to inner T.

Unwraps to the internal Arc<T>

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

The resulting type after dereferencing.

Dereferences the value.

Performs the conversion.

The associated error which can be returned.

Future that resolves to a Self.

Create a Self from request parts asynchronously.

Create a Self from request head asynchronously. Read more

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

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

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

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

🔬 This is a nightly-only experimental API. (toowned_clone_into)

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

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

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