1
0
mirror of https://github.com/actix/examples synced 2024-12-04 02:32:12 +01:00
examples/cookie-session/src/main.rs

43 lines
1.3 KiB
Rust
Raw Normal View History

2018-05-03 00:11:57 +02: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/master/redis-session)
//!
//! [User guide](https://actix.rs/book/actix-web/sec-9-middlewares.html#user-sessions)
2019-03-10 03:03:09 +01:00
use actix_session::{CookieSession, Session};
use actix_web::{middleware::Logger, web, App, HttpRequest, HttpServer, Result};
2018-05-03 00:11:57 +02:00
/// simple index handler with session
2019-03-10 03:03:09 +01:00
fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
2018-05-03 00:11:57 +02:00
println!("{:?}", req);
// RequestSession trait is used for session access
let mut counter = 1;
2019-03-10 03:03:09 +01:00
if let Some(count) = session.get::<i32>("counter")? {
2018-05-03 00:11:57 +02:00
println!("SESSION value: {}", count);
counter = count + 1;
2019-03-10 03:03:09 +01:00
session.set("counter", counter)?;
2018-05-03 00:11:57 +02:00
} else {
2019-03-10 03:03:09 +01:00
session.set("counter", counter)?;
2018-05-03 00:11:57 +02:00
}
Ok("welcome!")
}
2019-03-10 03:03:09 +01:00
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
2018-05-03 00:11:57 +02:00
env_logger::init();
2019-03-10 03:03:09 +01:00
HttpServer::new(|| {
2018-05-03 00:11:57 +02:00
App::new()
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(Logger::default())
2018-05-03 00:11:57 +02:00
// cookie session middleware
2019-03-26 04:29:00 +01:00
.wrap(CookieSession::signed(&[0; 32]).secure(false))
2019-03-10 03:03:09 +01:00
.service(web::resource("/").to(index))
})
.bind("127.0.0.1:8080")?
.run()
2018-05-03 00:11:57 +02:00
}