1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-23 23:51:06 +01:00
actix-extras/actix-session/examples/basic.rs

52 lines
1.6 KiB
Rust
Raw Permalink Normal View History

2024-03-13 00:30:06 +01:00
use actix_session::{storage::RedisSessionStore, Session, SessionMiddleware};
use actix_web::{cookie::Key, middleware, web, App, Error, HttpRequest, HttpServer, Responder};
use tracing::level_filters::LevelFilter;
use tracing_subscriber::EnvFilter;
2017-12-29 06:14:04 +01:00
/// simple handler
2019-12-15 19:04:47 +01:00
async fn index(req: HttpRequest, session: Session) -> Result<impl Responder, Error> {
2023-01-07 02:04:16 +01:00
println!("{req:?}");
2017-12-29 06:14:04 +01:00
// session
2019-03-29 19:31:48 +01:00
if let Some(count) = session.get::<i32>("counter")? {
2023-01-07 02:04:16 +01:00
println!("SESSION value: {count}");
session.insert("counter", count + 1)?;
2017-12-29 06:14:04 +01:00
} else {
session.insert("counter", 1)?;
2017-12-29 06:14:04 +01:00
}
2019-03-29 19:31:48 +01:00
Ok("Welcome!")
2017-12-29 06:14:04 +01:00
}
2022-02-03 23:33:47 +01:00
#[actix_web::main]
2019-12-15 19:04:47 +01:00
async fn main() -> std::io::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
2017-12-29 06:14:04 +01:00
// The signing key would usually be read from a configuration file/environment variables.
let signing_key = Key::generate();
tracing::info!("setting up Redis session storage");
2024-03-13 00:30:06 +01:00
let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
tracing::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || {
2018-05-08 19:12:57 +02:00
App::new()
2017-12-29 06:14:04 +01:00
// enable logger
2019-03-29 19:31:48 +01:00
.wrap(middleware::Logger::default())
2017-12-29 06:14:04 +01:00
// cookie session middleware
2024-03-13 00:30:06 +01:00
.wrap(SessionMiddleware::new(storage.clone(), signing_key.clone()))
2017-12-29 06:14:04 +01:00
// register simple route, handle all methods
2019-03-29 19:31:48 +01:00
.service(web::resource("/").to(index))
})
.bind(("127.0.0.1", 8080))?
2019-12-26 07:47:31 +01:00
.run()
2019-12-15 19:04:47 +01:00
.await
2017-12-29 06:14:04 +01:00
}