2020-09-06 11:45:51 +02:00
|
|
|
// <setup_mutable>
|
|
|
|
use actix_web::{web, App, HttpServer};
|
|
|
|
use std::sync::Mutex;
|
|
|
|
|
|
|
|
struct AppStateWithCounter {
|
|
|
|
counter: Mutex<i32>, // <- Mutex is necessary to mutate safely across threads
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn index(data: web::Data<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>
|
2020-09-12 17:21:54 +02:00
|
|
|
#[actix_web::main]
|
2020-09-06 11:45:51 +02:00
|
|
|
async fn main() -> std::io::Result<()> {
|
|
|
|
let counter = web::Data::new(AppStateWithCounter {
|
|
|
|
counter: Mutex::new(0),
|
|
|
|
});
|
|
|
|
|
|
|
|
HttpServer::new(move || {
|
|
|
|
// move counter into the closure
|
|
|
|
App::new()
|
|
|
|
// Note: using app_data instead of data
|
|
|
|
.app_data(counter.clone()) // <- register the created data
|
|
|
|
.route("/", web::get().to(index))
|
|
|
|
})
|
2020-09-12 17:21:54 +02:00
|
|
|
.bind("127.0.0.1:8080")?
|
2020-09-06 11:45:51 +02:00
|
|
|
.run()
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
// </make_app_mutable>
|