-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmutable_state.rs
35 lines (30 loc) · 1015 Bytes
/
mutable_state.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// <setup_mutable>
use ntex::web;
use std::sync::{Arc, Mutex};
struct AppStateWithCounter {
counter: Mutex<i32>, // <- Mutex is necessary to mutate safely across threads
}
async fn index(data: web::types::State<AppStateWithCounter>) -> String {
let mut counter = data.counter.lock().unwrap(); // <- get counter's MutexGuard
*counter += 1; // <- access counter inside MutexGuard
format!("Request number: {counter}") // <- response with count
}
// </setup_mutable>
// <make_app_mutable>
#[ntex::main]
async fn main() -> std::io::Result<()> {
// Note: app state created _outside_ HttpServer::new closure
let counter = Arc::new(AppStateWithCounter {
counter: Mutex::new(0),
});
web::HttpServer::new(move || {
// move counter into the closure
web::App::new()
.state(counter.clone()) // <- register the created data
.route("/", web::get().to(index))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
// </make_app_mutable>