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.
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2019-03-07 23:50:29 +01:00
|
|
|
use std::io;
|
|
|
|
use std::sync::{Arc, Mutex};
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2019-03-07 23:50:29 +01:00
|
|
|
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
|
2018-04-13 03:18:42 +02:00
|
|
|
|
|
|
|
/// simple handle
|
2019-03-17 04:23:09 +01:00
|
|
|
fn index(state: web::Data<Arc<Mutex<usize>>>, req: HttpRequest) -> HttpResponse {
|
2018-04-13 03:18:42 +02:00
|
|
|
println!("{:?}", req);
|
2019-03-07 23:50:29 +01:00
|
|
|
*(state.lock().unwrap()) += 1;
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2019-03-07 23:50:29 +01:00
|
|
|
HttpResponse::Ok().body(format!("Num of requests: {}", state.lock().unwrap()))
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
2019-03-07 23:50:29 +01:00
|
|
|
fn main() -> io::Result<()> {
|
|
|
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
2018-04-13 03:18:42 +02:00
|
|
|
env_logger::init();
|
|
|
|
|
2019-05-25 16:22:43 +02:00
|
|
|
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
|
2018-04-13 03:18:42 +02:00
|
|
|
// enable logger
|
2019-03-26 04:29:00 +01:00
|
|
|
.wrap(middleware::Logger::default())
|
2018-04-13 03:18:42 +02:00
|
|
|
// 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()
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|