2018-05-23 22:01:33 +02:00
|
|
|
// <setup>
|
2019-06-19 00:20:50 -04:00
|
|
|
use actix_web::{web, App, HttpServer};
|
2019-07-22 11:10:21 +06:00
|
|
|
use std::sync::Mutex;
|
2018-05-23 22:01:33 +02:00
|
|
|
|
|
|
|
// This struct represents state
|
|
|
|
struct AppState {
|
2019-07-15 16:35:50 +07:00
|
|
|
app_name: String,
|
2018-05-23 22:01:33 +02:00
|
|
|
}
|
|
|
|
|
2019-12-29 01:15:22 +09:00
|
|
|
async fn index(data: web::Data<AppState>) -> String {
|
2019-07-22 11:10:21 +06:00
|
|
|
let app_name = &data.app_name; // <- get app_name
|
2018-05-23 22:01:33 +02:00
|
|
|
|
2019-07-15 16:35:50 +07:00
|
|
|
format!("Hello {}!", app_name) // <- response with app_name
|
2018-05-23 22:01:33 +02:00
|
|
|
}
|
|
|
|
// </setup>
|
|
|
|
|
2019-07-15 16:35:50 +07:00
|
|
|
// <setup_mutable>
|
|
|
|
struct AppStateWithCounter {
|
|
|
|
counter: Mutex<i32>, // <- Mutex is necessary to mutate safely across threads
|
|
|
|
}
|
|
|
|
|
2019-12-29 01:15:22 +09:00
|
|
|
async fn _index(data: web::Data<AppStateWithCounter>) -> String {
|
2019-07-18 20:59:11 +07:00
|
|
|
let mut counter = data.counter.lock().unwrap(); // <- get counter's MutexGuard
|
2019-07-15 16:35:50 +07:00
|
|
|
*counter += 1; // <- access counter inside MutexGuard
|
|
|
|
|
|
|
|
format!("Request number: {}", counter) // <- response with count
|
|
|
|
}
|
|
|
|
// </setup_mutable>
|
|
|
|
|
|
|
|
// <make_app_mutable>
|
2019-12-29 01:15:22 +09:00
|
|
|
#[actix_rt::main]
|
|
|
|
async fn _main() -> std::io::Result<()> {
|
2019-07-22 11:10:21 +06:00
|
|
|
let counter = web::Data::new(AppStateWithCounter {
|
|
|
|
counter: Mutex::new(0),
|
|
|
|
});
|
2019-07-15 16:35:50 +07:00
|
|
|
|
2019-09-25 06:37:36 +02:00
|
|
|
HttpServer::new(move || { // move counter into the closure
|
|
|
|
App::new()
|
2019-12-29 01:15:22 +09:00
|
|
|
.app_data(counter.clone()) // <- register the created data
|
2019-09-25 06:37:36 +02:00
|
|
|
.route("/", web::get().to(_index))
|
|
|
|
})
|
2019-12-29 01:15:22 +09:00
|
|
|
.bind("127.0.0.1:8088")?
|
2019-09-25 06:37:36 +02:00
|
|
|
.run()
|
2019-12-29 01:15:22 +09:00
|
|
|
.await
|
2018-06-08 10:17:29 +02:00
|
|
|
}
|
2019-07-15 16:35:50 +07:00
|
|
|
// </make_app_mutable>
|
2018-06-08 10:17:29 +02:00
|
|
|
|
2019-06-19 00:20:50 -04:00
|
|
|
// <start_app>
|
2019-12-29 01:15:22 +09:00
|
|
|
#[actix_rt::main]
|
|
|
|
async fn main() -> std::io::Result<()> {
|
2019-06-13 03:24:25 -04:00
|
|
|
HttpServer::new(|| {
|
|
|
|
App::new()
|
2019-06-19 00:20:50 -04:00
|
|
|
.data(AppState {
|
2019-07-22 11:10:21 +06:00
|
|
|
app_name: String::from("Actix-web"),
|
2019-06-19 00:20:50 -04:00
|
|
|
})
|
|
|
|
.route("/", web::get().to(index))
|
2019-06-13 03:24:25 -04:00
|
|
|
})
|
2019-12-29 01:15:22 +09:00
|
|
|
.bind("127.0.0.1:8088")?
|
2019-07-15 17:12:37 +07:00
|
|
|
.run()
|
2019-12-29 01:15:22 +09:00
|
|
|
.await
|
2018-05-24 09:31:40 -07:00
|
|
|
}
|
2019-06-19 00:20:50 -04:00
|
|
|
// </start_app>
|