2022-03-05 23:22:14 +00:00
|
|
|
use actix_session::{storage::RedisActorSessionStore, Session, SessionMiddleware};
|
|
|
|
use actix_web::{cookie::Key, middleware, web, App, Error, HttpRequest, HttpServer, Responder};
|
2017-12-28 21:14:04 -08:00
|
|
|
|
|
|
|
/// simple handler
|
2019-12-16 00:04:47 +06:00
|
|
|
async fn index(req: HttpRequest, session: Session) -> Result<impl Responder, Error> {
|
2023-01-07 01:04:16 +00:00
|
|
|
println!("{req:?}");
|
2017-12-28 21:14:04 -08:00
|
|
|
|
|
|
|
// session
|
2019-03-29 11:31:48 -07:00
|
|
|
if let Some(count) = session.get::<i32>("counter")? {
|
2023-01-07 01:04:16 +00:00
|
|
|
println!("SESSION value: {count}");
|
2021-03-23 22:35:27 +00:00
|
|
|
session.insert("counter", count + 1)?;
|
2017-12-28 21:14:04 -08:00
|
|
|
} else {
|
2021-03-23 22:35:27 +00:00
|
|
|
session.insert("counter", 1)?;
|
2017-12-28 21:14:04 -08:00
|
|
|
}
|
|
|
|
|
2019-03-29 11:31:48 -07:00
|
|
|
Ok("Welcome!")
|
2017-12-28 21:14:04 -08:00
|
|
|
}
|
|
|
|
|
2022-02-03 22:33:47 +00:00
|
|
|
#[actix_web::main]
|
2019-12-16 00:04:47 +06:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2022-03-05 23:22:14 +00:00
|
|
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
2017-12-28 21:14:04 -08:00
|
|
|
|
2022-03-05 23:22:14 +00:00
|
|
|
// The signing key would usually be read from a configuration file/environment variables.
|
|
|
|
let signing_key = Key::generate();
|
|
|
|
|
|
|
|
log::info!("starting HTTP server at http://localhost:8080");
|
|
|
|
|
|
|
|
HttpServer::new(move || {
|
2018-05-08 10:12:57 -07:00
|
|
|
App::new()
|
2017-12-28 21:14:04 -08:00
|
|
|
// enable logger
|
2019-03-29 11:31:48 -07:00
|
|
|
.wrap(middleware::Logger::default())
|
2017-12-28 21:14:04 -08:00
|
|
|
// cookie session middleware
|
2022-03-05 23:22:14 +00:00
|
|
|
.wrap(SessionMiddleware::new(
|
|
|
|
RedisActorSessionStore::new("127.0.0.1:6379"),
|
|
|
|
signing_key.clone(),
|
|
|
|
))
|
2017-12-28 21:14:04 -08:00
|
|
|
// register simple route, handle all methods
|
2019-03-29 11:31:48 -07:00
|
|
|
.service(web::resource("/").to(index))
|
|
|
|
})
|
2022-03-05 23:22:14 +00:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2019-12-26 15:47:31 +09:00
|
|
|
.run()
|
2019-12-16 00:04:47 +06:00
|
|
|
.await
|
2017-12-28 21:14:04 -08:00
|
|
|
}
|