Skip to main content

basic/
cookie.rs

1use afire::{Content, Method, Response, Server, SetCookie};
2
3use crate::Example;
4
5// You can run this example with `cargo run --example basic -- cookie`
6
7// This example shows how you can work with cookies using the Cookie and SetCookie structs
8// We will make a route to show all cookies and a route to set a cookie
9
10pub struct Cookie;
11
12impl Example for Cookie {
13    fn name(&self) -> &'static str {
14        "cookie"
15    }
16
17    fn exec(&self) {
18        // Create a new Server instance on localhost port 8080
19        let mut server = Server::<()>::new([127, 0, 0, 1], 8080);
20
21        // Define a route to show request cookies as a table
22        server.route(Method::GET, "/", |req| {
23            // Return all cookies in a *messy* html table
24            let mut html = String::new();
25            html.push_str("<style>table, th, td {border:1px solid black;}</style>");
26            html.push_str("<table>");
27            html.push_str("<tr><th>Name</th><th>Value</th></tr>");
28            for cookie in &*req.cookies {
29                html.push_str("<tr><td>");
30                html.push_str(&cookie.name);
31                html.push_str("</td><td>");
32                html.push_str(&cookie.value);
33                html.push_str("</td></tr>");
34            }
35            html.push_str("</table>");
36
37            Response::new().text(html).content(Content::HTML)
38        });
39
40        // Set a cookie defined in the Query
41        server.route(Method::GET, "/set", |req| {
42            // Create a new cookie
43            let cookie = SetCookie::new(
44                req.query.get("name").unwrap_or("test"),
45                req.query.get("value").unwrap_or("test"),
46            )
47            // Set some options
48            .max_age(60 * 60)
49            .path("/");
50
51            let body = format!(
52                "Set Cookie '{}' to '{}'",
53                cookie.cookie.name, cookie.cookie.value
54            );
55
56            // Set the cookie
57            Response::new()
58                .text(body)
59                .content(Content::HTML)
60                .cookie(cookie)
61        });
62
63        // Now goto http://localhost:8080/set?name=hello&value=world
64        // Then goto http://localhost:8080/ and you should see a table with the cookie
65
66        // Start the server in single threaded mode
67        // This will block the current thread
68        server.start().unwrap();
69    }
70}