Struct ntex::web::types::Data [−][src]
pub struct Data<T>(_);
Expand description
Application data.
Application data is an arbitrary data attached to the app.
Application data is available to all routes and could be added
during application configuration process
with App::data()
method.
Application data could 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
type
uses Arc
. if your data implements Send
+ Sync
traits you can
use web::types::Data::new()
and avoid double Arc
.
If route data is not set for a handler, using Data<T>
extractor would
cause Internal Server Error response.
use std::sync::Mutex;
use ntex::web::{self, App, HttpResponse};
struct MyData {
counter: usize,
}
/// Use `Data<T>` extractor to access data in handler.
async fn index(data: web::types::Data<Mutex<MyData>>) -> HttpResponse {
let mut data = data.lock().unwrap();
data.counter += 1;
HttpResponse::Ok().into()
}
fn main() {
let data = web::types::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
Create new Data
instance.
Internally Data
type uses Arc
. if your data implements
Send
+ Sync
traits you can use web::types::Data::new()
and
avoid double Arc
.
Convert to the internal Arc
Trait Implementations
type Error = DataExtractorError
type Error = DataExtractorError
The associated error which can be returned.
Convert request to a Self
Convert request to a Self Read more
Auto Trait Implementations
impl<T> RefUnwindSafe for Data<T> where
T: RefUnwindSafe,
impl<T> UnwindSafe for Data<T> where
T: RefUnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
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