1
0
mirror of https://github.com/actix/examples synced 2024-12-01 01:24:35 +01:00
examples/state/src/main.rs

45 lines
1.6 KiB
Rust
Raw Normal View History

2018-05-02 15:20:43 +02:00
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
2019-03-17 04:23:09 +01:00
//! Application may have multiple data objects that are shared across
//! all handlers within same Application. Data could be added
//! with `App::data()` method, multiple different data objects could be added.
2018-05-02 15:20:43 +02:00
//!
2018-05-08 20:08:43 +02:00
//! > **Note**: http server accepts an application factory rather than an
//! application > instance. Http server constructs an application instance for
2019-03-17 04:23:09 +01:00
//! each thread, > thus application data
//! > must be constructed multiple times. If you want to share data between
2018-05-08 20:08:43 +02:00
//! different > threads, a shared object should be used, e.g. `Arc`.
2018-05-02 15:20:43 +02:00
//!
//! Check [user guide](https://actix.rs/book/actix-web/sec-2-application.html) for more info.
2019-03-07 23:50:29 +01:00
use std::io;
use std::sync::{Arc, Mutex};
2019-03-07 23:50:29 +01:00
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
/// simple handle
2019-03-17 04:23:09 +01:00
fn index(state: web::Data<Arc<Mutex<usize>>>, req: HttpRequest) -> HttpResponse {
println!("{:?}", req);
2019-03-07 23:50:29 +01:00
*(state.lock().unwrap()) += 1;
2019-03-07 23:50:29 +01:00
HttpResponse::Ok().body(format!("Num of requests: {}", state.lock().unwrap()))
}
2019-03-07 23:50:29 +01:00
fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let counter = Arc::new(Mutex::new(0usize));
2019-03-07 23:50:29 +01:00
2018-10-27 13:03:02 +02:00
//move is necessary to give closure below ownership of counter
2019-03-07 23:50:29 +01:00
HttpServer::new(move || {
App::new()
2019-03-17 04:23:09 +01:00
.data(counter.clone()) // <- create app with shared state
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(middleware::Logger::default())
// register simple handler, handle all methods
2019-03-07 23:50:29 +01:00
.service(web::resource("/").to(index))
})
.bind("127.0.0.1:8080")?
.run()
}