2018-05-02 15:20:43 +02:00
|
|
|
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
|
2018-04-13 03:18:42 +02:00
|
|
|
//! There are two level of statefulness in actix-web. Application has state
|
|
|
|
//! that is shared across all handlers within same Application.
|
|
|
|
//! And individual handler can have state.
|
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
|
|
|
|
//! each thread, > thus application state
|
|
|
|
//! > must be constructed multiple times. If you want to share state between
|
|
|
|
//! 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
|
|
|
|
|
|
|
extern crate actix;
|
|
|
|
extern crate actix_web;
|
|
|
|
extern crate env_logger;
|
|
|
|
|
2018-10-14 19:56:25 +02:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::sync::Mutex;
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2018-05-08 20:08:43 +02:00
|
|
|
use actix_web::{middleware, server, App, HttpRequest, HttpResponse};
|
2018-04-13 03:18:42 +02:00
|
|
|
|
|
|
|
/// Application state
|
|
|
|
struct AppState {
|
2018-10-14 19:56:25 +02:00
|
|
|
counter: Arc<Mutex<usize>>,
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// simple handle
|
2018-07-16 08:36:53 +02:00
|
|
|
fn index(req: &HttpRequest<AppState>) -> HttpResponse {
|
2018-04-13 03:18:42 +02:00
|
|
|
println!("{:?}", req);
|
2018-10-14 19:56:25 +02:00
|
|
|
*(req.state().counter.lock().unwrap()) += 1;
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2018-10-14 19:56:25 +02:00
|
|
|
HttpResponse::Ok().body(format!("Num of requests: {}", req.state().counter.lock().unwrap()))
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
::std::env::set_var("RUST_LOG", "actix_web=info");
|
|
|
|
env_logger::init();
|
|
|
|
let sys = actix::System::new("ws-example");
|
|
|
|
|
2018-10-27 13:03:02 +02:00
|
|
|
let counter = Arc::new(Mutex::new(0));
|
|
|
|
//move is necessary to give closure below ownership of counter
|
|
|
|
server::new(move || {
|
|
|
|
App::with_state(AppState{counter: counter.clone()}) // <- create app with shared state
|
2018-04-13 03:18:42 +02:00
|
|
|
// enable logger
|
|
|
|
.middleware(middleware::Logger::default())
|
|
|
|
// register simple handler, handle all methods
|
2018-05-02 15:20:43 +02:00
|
|
|
.resource("/", |r| r.f(index))
|
|
|
|
}).bind("127.0.0.1:8080")
|
|
|
|
.unwrap()
|
2018-04-13 03:18:42 +02:00
|
|
|
.start();
|
|
|
|
|
|
|
|
println!("Started http server: 127.0.0.1:8080");
|
|
|
|
let _ = sys.run();
|
|
|
|
}
|