Struct ajars_actix_web::actix_web::web::Data [−][src]
pub struct Data<T>(_)
where
T: ?Sized;
Expand description
Application data.
Application level data is a piece of arbitrary data attached to the app, scope, or resource.
Application data is available to all routes and can be added during the application
configuration process via App::data()
.
Application data can be accessed by using Data<T>
extractor where T
is data type.
Note: HTTP server accepts an application factory rather than an application instance. HTTP
server constructs an application instance for each thread, thus application data must be
constructed multiple times. If you want to share data between different threads, a shareable
object should be used, e.g. Send + Sync
. Application data does not need to be Send
or Sync
. Internally Data
uses Arc
.
If route data is not set for a handler, using Data<T>
extractor would cause Internal
Server Error response.
Examples
use std::sync::Mutex;
use actix_web::{web, App, HttpResponse, Responder};
struct MyData {
counter: usize,
}
/// Use the `Data<T>` extractor to access data in a handler.
async fn index(data: web::Data<Mutex<MyData>>) -> impl Responder {
let mut data = data.lock().unwrap();
data.counter += 1;
HttpResponse::Ok()
}
fn main() {
let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));
let app = App::new()
// Store `MyData` in application storage.
.app_data(data.clone())
.service(
web::resource("/index.html").route(
web::get().to(index)));
}
Implementations
Methods from Deref<Target = Arc<T>>
Trait Implementations
pub fn from_request(
req: &HttpRequest,
&mut Payload<Pin<Box<dyn Stream<Item = Result<Bytes, PayloadError>> + 'static, Global>>>
) -> <Data<T> as FromRequest>::Future
pub fn from_request(
req: &HttpRequest,
&mut Payload<Pin<Box<dyn Stream<Item = Result<Bytes, PayloadError>> + 'static, Global>>>
) -> <Data<T> as FromRequest>::Future
Create a Self from request parts asynchronously.
Create a Self from request head asynchronously. Read more
pub fn serialize<S>(
&self,
serializer: S
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer,
pub fn serialize<S>(
&self,
serializer: S
) -> Result<<S as Serializer>::Ok, <S as Serializer>::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> UnwindSafe for Data<T> where
T: RefUnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
type Output = T
type Output = T
Should always be Self