pub struct State<T>(/* private fields */);Expand description
Application state.
Application state is an arbitrary data attached to the app.
Application state is available to all routes and could be added
during application configuration process
with App::state() method.
Application state could be accessed by using State<T>
extractor where T is state 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 state between different
threads, a shareable object should be used, e.g. Send + Sync. Application
state does not need to be Send or Sync.
If state is not set for a handler, using State<T> extractor would
cause Internal Server Error response.
use std::sync::{Arc, Mutex};
use ntex::web::{self, App, HttpResponse};
struct MyState {
counter: usize,
}
/// Use `State<T>` extractor to access data in handler.
async fn index(st: web::types::State<Arc<Mutex<MyState>>>) -> HttpResponse {
let mut data = st.lock().unwrap();
data.counter += 1;
HttpResponse::Ok().into()
}
fn main() {
let st = Arc::new(Mutex::new(MyState{ counter: 0 }));
let app = App::new()
// Store `MyState` in application storage.
.state(st.clone())
.service(
web::resource("/index.html").route(
web::get().to(index)));
}