1
0
mirror of https://github.com/actix/actix-website synced 2024-11-28 10:32:38 +01:00
actix-website/examples/middleware/src/user_sessions.rs

38 lines
1.0 KiB
Rust
Raw Normal View History

2020-09-12 17:21:54 +02:00
#![allow(dead_code)]
2019-06-17 22:57:57 +02:00
// <user-session>
2022-10-26 12:14:06 +02:00
use actix_session::{Session, SessionMiddleware, storage::CookieSessionStore};
use actix_web::{web, App, Error, HttpResponse, HttpServer, cookie::Key};
2019-06-17 22:57:57 +02:00
2019-12-28 18:03:17 +01:00
async fn index(session: Session) -> Result<HttpResponse, Error> {
2019-06-26 08:59:20 +02:00
// access session data
2019-06-17 22:57:57 +02:00
if let Some(count) = session.get::<i32>("counter")? {
2022-02-26 04:56:24 +01:00
session.insert("counter", count + 1)?;
2019-06-17 22:57:57 +02:00
} else {
2022-02-26 04:56:24 +01:00
session.insert("counter", 1)?;
2019-06-17 22:57:57 +02:00
}
2019-06-26 08:59:20 +02:00
Ok(HttpResponse::Ok().body(format!(
"Count is {:?}!",
session.get::<i32>("counter")?.unwrap()
)))
2019-06-17 22:57:57 +02:00
}
2020-09-12 17:21:54 +02:00
#[actix_web::main]
2019-12-28 18:03:17 +01:00
async fn main() -> std::io::Result<()> {
2019-06-17 22:57:57 +02:00
HttpServer::new(|| {
App::new()
2019-06-26 08:59:20 +02:00
.wrap(
2022-10-26 12:14:06 +02:00
// create cookie based session middleware
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
.cookie_secure(false)
.build()
2019-06-26 08:59:20 +02:00
)
2019-06-17 22:57:57 +02:00
.service(web::resource("/").to(index))
})
2022-02-26 04:56:24 +01:00
.bind(("127.0.0.1", 8080))?
2019-06-17 22:57:57 +02:00
.run()
2019-12-28 18:03:17 +01:00
.await
2019-06-17 22:57:57 +02:00
}
// </user-session>