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

46 lines
1.4 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)
//!
2019-07-11 10:47:41 +02:00
//! [User guide](https://actix.rs/docs/middleware/#user-sessions)
2018-05-03 00:11:57 +02:00
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-12-07 18:59:24 +01:00
async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
log::info!("{:?}", req);
2018-05-03 00:11:57 +02:00
// 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")? {
log::info!("SESSION value: {}", count);
2018-05-03 00:11:57 +02:00
counter = count + 1;
session.insert("counter", counter)?;
2018-05-03 00:11:57 +02:00
} else {
session.insert("counter", counter)?;
2018-05-03 00:11:57 +02:00
}
Ok("welcome!")
}
2020-09-12 17:49:45 +02:00
#[actix_web::main]
2019-12-07 18:59:24 +01:00
async fn main() -> std::io::Result<()> {
2019-03-10 03:03:09 +01:00
std::env::set_var("RUST_LOG", "actix_web=info");
2018-05-03 00:11:57 +02:00
env_logger::init();
log::info!("Starting http server: 127.0.0.1:8080");
2018-05-03 00:11:57 +02:00
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")?
2019-12-25 17:48:33 +01:00
.run()
2019-12-07 18:59:24 +01:00
.await
2018-05-03 00:11:57 +02:00
}