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

36 lines
927 B
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>
use actix_session::{CookieSession, Session};
2019-06-26 08:59:20 +02:00
use actix_web::{web, App, Error, HttpResponse, HttpServer};
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(
CookieSession::signed(&[0; 32]) // <- create cookie based session middleware
.secure(false),
)
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>