1
0
mirror of https://github.com/actix/examples synced 2025-03-14 16:56:25 +01:00

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