1
0
mirror of https://github.com/actix/examples synced 2025-01-23 06:14:35 +01:00

60 lines
1.8 KiB
Rust
Raw Normal View History

2018-05-02 15:11:57 -07:00
//! Example of cookie based session
//! Session data is stored in cookie, it is limited to 4kb
//!
//! [Redis session example](https://github.com/actix/examples/tree/HEAD/auth/redis-session)
2018-05-02 15:11:57 -07:00
//!
2019-07-11 10:47:41 +02:00
//! [User guide](https://actix.rs/docs/middleware/#user-sessions)
2018-05-02 15:11:57 -07:00
2022-08-28 18:39:28 +01:00
use actix_session::{
config::PersistentSession, storage::CookieSessionStore, Session, SessionMiddleware,
};
use actix_web::{
cookie::{self, Key},
middleware::Logger,
web, App, HttpRequest, HttpServer, Result,
};
2018-05-02 15:11:57 -07:00
/// simple index handler with session
2019-12-07 23:59:24 +06:00
async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
log::info!("{req:?}");
2018-05-02 15:11:57 -07:00
// RequestSession trait is used for session access
let mut counter = 1;
2019-03-09 18:03:09 -08:00
if let Some(count) = session.get::<i32>("counter")? {
log::info!("SESSION value: {count}");
2018-05-02 15:11:57 -07:00
counter = count + 1;
session.insert("counter", counter)?;
2018-05-02 15:11:57 -07:00
} else {
session.insert("counter", counter)?;
2018-05-02 15:11:57 -07:00
}
Ok("welcome!")
}
2020-09-12 16:49:45 +01:00
#[actix_web::main]
2019-12-07 23:59:24 +06:00
async fn main() -> std::io::Result<()> {
2023-03-14 03:11:49 +00:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080");
2018-05-02 15:11:57 -07:00
2019-03-09 18:03:09 -08:00
HttpServer::new(|| {
2018-05-02 15:11:57 -07:00
App::new()
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(Logger::default())
2018-05-02 15:11:57 -07:00
// cookie session middleware
.wrap(
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
.cookie_secure(false)
2022-08-28 18:39:28 +01:00
// customize session and cookie expiration
.session_lifecycle(
PersistentSession::default().session_ttl(cookie::time::Duration::hours(2)),
)
.build(),
)
2019-03-09 18:03:09 -08:00
.service(web::resource("/").to(index))
})
2022-02-17 20:22:36 +00:00
.bind(("127.0.0.1", 8080))?
2019-12-25 20:48:33 +04:00
.run()
2019-12-07 23:59:24 +06:00
.await
2018-05-02 15:11:57 -07:00
}