1
0
mirror of https://github.com/actix/actix-website synced 2024-11-24 16:52:59 +01:00
actix-website/examples/middleware/src/user_sessions.rs
2022-10-26 11:14:06 +01:00

38 lines
1.0 KiB
Rust

#![allow(dead_code)]
// <user-session>
use actix_session::{Session, SessionMiddleware, storage::CookieSessionStore};
use actix_web::{web, App, Error, HttpResponse, HttpServer, cookie::Key};
async fn index(session: Session) -> Result<HttpResponse, Error> {
// access session data
if let Some(count) = session.get::<i32>("counter")? {
session.insert("counter", count + 1)?;
} else {
session.insert("counter", 1)?;
}
Ok(HttpResponse::Ok().body(format!(
"Count is {:?}!",
session.get::<i32>("counter")?.unwrap()
)))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(
// create cookie based session middleware
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
.cookie_secure(false)
.build()
)
.service(web::resource("/").to(index))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
// </user-session>