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
|
|
|
//!
|
2019-11-14 21:16:48 +01:00
|
|
|
//! Check [user guide](https://actix.rs/docs/application/#state) for more info.
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2019-03-07 23:50:29 +01:00
|
|
|
use std::io;
|
2019-06-06 12:47:40 +02:00
|
|
|
use std::sync::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-12-07 18:59:24 +01:00
|
|
|
async fn index(state: web::Data<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-12-07 18:59:24 +01:00
|
|
|
#[actix_rt::main]
|
|
|
|
async fn main() -> io::Result<()> {
|
2019-03-07 23:50:29 +01:00
|
|
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
2018-04-13 03:18:42 +02:00
|
|
|
env_logger::init();
|
|
|
|
|
2019-06-06 12:47:40 +02:00
|
|
|
let counter = web::Data::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-12-20 17:30:26 +01:00
|
|
|
.app_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")?
|
2019-12-25 17:48:33 +01:00
|
|
|
.run()
|
2019-12-07 18:59:24 +01:00
|
|
|
.await
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|