Struct rocket_session::Session

source ·
pub struct Session<'a, D>where
    D: 'static + Sync + Send + Default,
{ /* private fields */ }
Expand description

Session instance

To access the active session, simply add it as an argument to a route function.

Sessions are started, restored, or expired in the FromRequest::from_request() method when a Session is prepared for one of the route functions.

Implementations§

Create the session fairing.

You can configure the session store by calling chained methods on the returned value before passing it to rocket.attach()

Examples found in repository?
examples/dog_list/main.rs (line 12)
10
11
12
13
14
fn rocket() -> _ {
    rocket::build()
        .attach(Session::fairing())
        .mount("/", routes![index, add, remove])
}
More examples
Hide additional examples
examples/minimal/main.rs (line 12)
9
10
11
12
13
14
fn rocket() -> _ {
    // This session expires in 15 seconds as a demonstration of session configuration
    rocket::build()
        .attach(Session::fairing().with_lifetime(Duration::from_secs(15)))
        .mount("/", routes![index])
}
examples/visit_counter/main.rs (line 24)
21
22
23
24
25
26
27
28
29
30
31
32
33
fn rocket() -> _ {
    rocket::build()
        .attach(
            Session::fairing()
                // 10 seconds of inactivity until session expires
                // (wait 10s and refresh, the numbers will reset)
                .with_lifetime(Duration::from_secs(10))
                // custom cookie name and length
                .with_cookie_name("my_cookie")
                .with_cookie_len(20),
        )
        .mount("/", routes![index, about])
}

Clear session data (replace the value with default)

Access the session’s data using a closure.

The closure is called with the data value as a mutable argument, and can return any value to be is passed up to the caller.

Examples found in repository?
examples/minimal/main.rs (lines 18-25)
17
18
19
20
21
22
23
24
25
26
27
28
fn index(session: Session) -> String {
    let count = session.tap(|n| {
        // Change the stored value (it is &mut)
        *n += 1;

        // Return something to the caller.
        // This can be any type, 'tap' is generic.
        *n
    });

    format!("{} visits", count)
}
More examples
Hide additional examples
examples/visit_counter/main.rs (lines 41-53)
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
fn index(session: Session) -> RawHtml<String> {
    // Here we build the entire response inside the 'tap' closure.

    // While inside, the session is locked to parallel changes, e.g.
    // from a different browser tab.
    session.tap(|sess| {
        sess.visits1 += 1;

        RawHtml(format!(
            r##"
                <!DOCTYPE html>
                <h1>Home</h1>
                <a href="/">Refresh</a> &bull; <a href="/about/">go to About</a>
                <p>Visits: home {}, about {}</p>
            "##,
            sess.visits1, sess.visits2
        ))
    })
}

#[get("/about")]
fn about(session: Session) -> RawHtml<String> {
    // Here we return a value from the tap function and use it below
    let count = session.tap(|sess| {
        sess.visits2 += 1;
        sess.visits2
    });

    RawHtml(format!(
        r##"
            <!DOCTYPE html>
            <h1>About</h1>
            <a href="/about">Refresh</a> &bull; <a href="/">go home</a>
            <p>Page visits: {}</p>
        "##,
        count
    ))
}
examples/dog_list/main.rs (lines 31-38)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
fn index(session: Session) -> RawHtml<String> {
    let mut page = String::new();
    page.push_str(
        r#"
            <!DOCTYPE html>
            <h1>My Dogs</h1>

            <form method="POST" action="/add">
            Add Dog: <input type="text" name="name"> <input type="submit" value="Add">
            </form>

            <ul>
        "#,
    );
    session.tap(|sess| {
        for (n, dog) in sess.iter().enumerate() {
            page.push_str(&format!(
                r#"<li>&#x1F436; {} <a href="/remove/{}">Remove</a></li>"#,
                dog, n
            ));
        }
    });
    page.push_str("</ul>");
    RawHtml(page)
}

#[post("/add", data = "<dog>")]
fn add(session: Session, dog: String) -> Redirect {
    session.tap(move |sess| {
        sess.push(dog);
    });
    Redirect::found("/")
}

#[get("/remove/<dog>")]
fn remove(session: Session, dog: usize) -> Redirect {
    session.tap(|sess| {
        if dog < sess.len() {
            sess.remove(dog);
        }
    });
    Redirect::found("/")
}

Trait Implementations§

Formats the value using the given formatter. Read more
The associated error to be returned if derivation fails.
Derives an instance of Self from the incoming request metadata. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Converts self into a collection.
Should always be Self
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more