Struct fe_session::FeSession [] [src]

pub struct FeSession<T: 'static> {
    // some fields omitted
}

This object holds information about the session for the current request.

FeSession can either be pulled directly out of the request or you can use the convenience functions in FeSessionRequest.

Examples

Accessing from directly from the request.

use std::sync::{Arc, Mutex};
use std::fmt::Write;
use iron::{Iron, Chain, Request, Response};
use iron::status::Status;
use fe_session::{FeSessionStorage, FeSession, FeConnection, FeSessionState};
use time::*;

let mut chain = Chain::new(|req : &mut Request| {
    let mut session = req.extensions.get_mut::<FeSession<usize>>().unwrap().clone();
    let mut result  = String::new();

    match session.state() {
        FeSessionState::Expired => { // Old session expired, create a new one.
            req.extensions.insert::<FeSession<usize>>(
                FeSession::new(
                    None,
                    FeSessionState::Active,
                    get_time(),
                    Some(Arc::new(Mutex::new(0)))
                    )
                );
        },
        FeSessionState::None => { // No session, create a new one.
            req.extensions.insert::<FeSession<usize>>(
                FeSession::new(
                    None,
                    FeSessionState::Active,
                    get_time(),
                    Some(Arc::new(Mutex::new(0)))
                    )
                );
           write!(result, "{}", 0).unwrap();
        },
        FeSessionState::Active => {
            let mut count = session.get();

            *count += 1;
            write!(result, "{}", *count).unwrap();
        }
    }
    Ok(Response::with((Status::Ok, result)))
});

chain.around(FeSessionStorage::<usize>::new());

let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();

let mut conn1 = FeConnection::new("localhost", 3000);
let mut conn2 = FeConnection::new("localhost", 3000);

assert_eq!(conn1.get_string("/"), "0");
assert_eq!(conn2.get_string("/"), "0");
assert_eq!(conn1.get_string("/"), "1");
assert_eq!(conn1.get_string("/"), "2");
assert_eq!(conn2.get_string("/"), "1");

iron.close().unwrap();

Or the recommended way using FeSessionRequest.

use std::fmt::Write;
use iron::{Iron, Chain, Request, Response};
use iron::status::Status;
use fe_session::{FeSessionStorage, FeConnection, FeSessionRequest, FeSessionState};

let mut chain = Chain::new(|req : &mut Request| {
    let mut session = req.get_session::<usize>();
    let mut result  = String::new();

    match session.state() {
        FeSessionState::Expired => { // Old session expired, create a new one.
            req.create_session(0 as usize);
        },
        FeSessionState::None => { // No session, create a new one.
           req.create_session(0 as usize);
           write!(result, "{}", 0).unwrap();
        },
        FeSessionState::Active => {
            let mut count = session.get();

            *count += 1;
            write!(result, "{}", *count).unwrap();
        }
    }
    Ok(Response::with((Status::Ok, result)))
});

chain.around(FeSessionStorage::<usize>::new());

let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();

let mut conn1 = FeConnection::new("localhost", 3000);
let mut conn2 = FeConnection::new("localhost", 3000);

assert_eq!(conn1.get_string("/"), "0");
assert_eq!(conn2.get_string("/"), "0");
assert_eq!(conn1.get_string("/"), "1");
assert_eq!(conn1.get_string("/"), "2");
assert_eq!(conn2.get_string("/"), "1");

iron.close().unwrap();

Methods

impl<T> FeSession<T>

fn new(key: Option<u32>, state: FeSessionState, last_accessed: Timespec, session: Option<Arc<Mutex<T>>>) -> FeSession<T>

Creates a new instance of the object.

Most clients probably won't need to use this function. Intead they should use the method exported by FeSessionRequest.

If you are calling this function manually the key should be set to None. If this is not set to None then there is a chance the session won't be saved.

For the state only only FeSessionState::None and FeSessionState::Active make sense however setting it to FeSessionState::Expired will not cause any issues.

Examples

Manually changing the session.

use std::sync::{Arc, Mutex};
use iron::{Iron, Chain, Request, Response};
use iron::status::Status;
use fe_session::{FeSessionStorage, FeSession, FeConnection, FeSessionState};
use time::get_time;

struct MySession;

let mut chain = Chain::new(|req : &mut Request| {

    if req.url.path()[0] == "clear" {
        req.extensions.insert::<FeSession<MySession>>(
            FeSession::new(None, FeSessionState::None, get_time(), None)
            );
        Ok(Response::with((Status::Ok, "cleared")))
    }
    else {
        req.extensions.insert::<FeSession<MySession>>(
            FeSession::new(
                None,
                FeSessionState::Active,
                get_time(),
                Some(Arc::new(Mutex::new(MySession)))
                )
            );
        Ok(Response::with((Status::Ok, "new")))
    }
});

chain.around(FeSessionStorage::<usize>::new());

let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();

let mut conn = FeConnection::new("localhost", 3000);

assert_eq!(conn.get_string("/clear"), "cleared");
assert_eq!(conn.get_string("/"), "new");

iron.close().unwrap();

Recommended way of changing the session.

use iron::{Iron, Chain, Request, Response};
use iron::status::Status;
use fe_session::{FeSessionStorage, FeConnection, FeSessionRequest};

struct MySession;

let mut chain = Chain::new(|req : &mut Request| {

    if req.url.path()[0] == "clear" {
        req.clear_session::<MySession>();
        Ok(Response::with((Status::Ok, "cleared")))
    }
    else {
        req.create_session(MySession);
        Ok(Response::with((Status::Ok, "new")))
    }
});

chain.around(FeSessionStorage::<usize>::new());

let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();

let mut conn = FeConnection::new("localhost", 3000);

assert_eq!(conn.get_string("/clear"), "cleared");
assert_eq!(conn.get_string("/"), "new");

iron.close().unwrap();

Panics

If the state is set to FeSessionState::Active but the session is None this method will panic.

fn key(&self) -> Option<u32>

Returns the session key for this session if it is defined. This is normally defined for an active session. However if a session is newly created it will not be created until the request has been completed.

fn state(&self) -> FeSessionState

Returns the current state of the session.

fn last_accessed(&self) -> &Timespec

Returns the time we last processed a request for this session.

fn poisoned(&self) -> bool

Returns true if the mutex protecting the session is poisoned. This means we've panicked while holding the session mutex. This value does not get set in a reuqest until the get() method is called.

fn get(&mut self) -> MutexGuard<T>

Acquires the mutex for the session and returns the MutexGuard. This means that any other requests that want to modify the session will be blocked until the MutexGuard is destroyed.

Examples

use std::fmt::Write;
use std::sync::{Arc, Mutex};
use iron::{Iron, Chain, Request, Response};
use iron::status::Status;
use fe_session::{FeSessionStorage, FeSession, FeConnection, FeSessionRequest, FeSessionState};

let mut chain = Chain::new(|req : &mut Request| {
    let mut session = req.get_session::<usize>();
    let mut result  = String::new();

    match session.state() {
        FeSessionState::Expired => { // Old session expired, create a new one.
            req.create_session(0 as usize);
        },
        FeSessionState::None => { // No session, create a new one.
           req.create_session(0 as usize);
           write!(result, "{}", 0).unwrap();
        },
        FeSessionState::Active => {
            let mut count = session.get();

            *count += 1;
            write!(result, "{}", *count).unwrap();
        }
    }
    Ok(Response::with((Status::Ok, result)))
});

chain.around(FeSessionStorage::<usize>::new());

let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();

let mut conn1 = FeConnection::new("localhost", 3000);
let mut conn2 = FeConnection::new("localhost", 3000);

assert_eq!(conn1.get_string("/"), "0");
assert_eq!(conn2.get_string("/"), "0");
assert_eq!(conn1.get_string("/"), "1");
assert_eq!(conn1.get_string("/"), "2");
assert_eq!(conn2.get_string("/"), "1");

iron.close().unwrap();

Panics

This method will panic if the state is not FeSessionState::Active.

fn raw(self) -> Arc<Mutex<T>>

Destroys the object and returns Arc> protecting the user's session.

Panics

This method will panic if the state is not FeSessionState::Active.

Trait Implementations

impl<T> Clone for FeSession<T>

fn clone(&self) -> FeSession<T>

fn clone_from(&mut self, source: &FeSession<T>)

impl<T: Any> Key for FeSession<T>

type Value = FeSession<T>

Derived Implementations

impl<T: Debug + 'static> Debug for FeSession<T>

fn fmt(&self, __arg_0: &mut Formatter) -> Result