1
0
mirror of https://github.com/actix/actix-website synced 2024-12-01 03:24:36 +01:00
actix-website/examples/application/src/state.rs

57 lines
1.3 KiB
Rust
Raw Normal View History

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