#session

iron_session

Session middleware for the iron framework

4 releases

Uses old Rust 2015

0.0.4 Mar 5, 2016
0.0.3 Mar 5, 2016
0.0.2 Mar 5, 2016
0.0.1 Mar 5, 2016

#213 in #session

MIT license

10KB
144 lines

Session middleware for the Iron web framework.

The Sessions struct is used to create the new session middleware.

Examples

Create and link a session:

#
#
#
    // create the chain that the session middleware will be linked in.
    let mut chain = Chain::new(handler);

    // create the session middleware.
    let store: HashSessionStore<TypeMapSession> = HashSessionStore::new();
    chain.around(Sessions::new(String::from("secret").into_bytes(), store));

Access the session data in a handler:

#
// Create a key type that we can associate with a value type.
struct Counter;

// implement the Key trait which associates u64 with Counter
impl Key for Counter { type Value = u64;}

// iron request handler
fn create(req: &mut Request) -> IronResult<Response> {

    // get the TypeMap for our session
    let lock = req.extensions.get::<TypeMapSession>().unwrap();

    // we want to write to the map, so get a write lock on it.
    let mut map = lock.write().unwrap();

    // if there was no counter object in the map, create one
    if let None = map.get::<Counter>() {
        map.insert::<Counter>(0);
    }

    // get a mutable reference to the u64 inside the map
    let mut count = map.get_mut::<Counter>().unwrap();
    *count += 1;

    // create a message with our hitcount and return in in a response
    let message = format!("hit count: {}", count);
    let mut res = Response::new();


    res.set_mut(status::Ok);
    res.set_mut(message);
    Ok(res)
}

Dependencies

~6.5MB
~136K SLoC