1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
use askama::Template;
use trillium::Conn;
use trillium_askama::AskamaConnExt;
use trillium_aws_lambda::LambdaConnExt;
use trillium_cookies::CookiesHandler;
use trillium_logger::Logger;
use trillium_router::{Router, RouterConnExt};
use trillium_sessions::{CookieStore, SessionConnExt, SessionHandler};

#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate<'a> {
    name: &'a str,
}

fn main() {
    env_logger::init();
    trillium_aws_lambda::run((
        Logger::new(),
        CookiesHandler::new(),
        SessionHandler::new(CookieStore::new(), b"01234567890123456789012345678901123"),
        |conn: Conn| async move {
            let count = conn.session().get::<usize>("count").unwrap_or_default();
            let request_id = conn.lambda_context().request_id.clone();
            conn.with_response_header("request-count", count.to_string())
                .with_response_header("request-id", request_id)
                .with_session("count", count + 1)
        },
        Router::new()
            .get("/always-hi", "hi")
            .post("/", |mut conn: Conn| async move {
                let body = conn.request_body_string().await.unwrap();
                conn.ok(format!("request body: {body}"))
            })
            .get("/template/:name", |conn: Conn| async move {
                if let Some(name) = conn.param("name").map(String::from) {
                    conn.render(HelloTemplate { name: &name })
                } else {
                    conn
                }
            })
            .get("/", |conn: Conn| async move { conn.ok("hello world") })
            .get("/hello/:planet", |conn: Conn| async move {
                if let Some(planet) = conn.param("planet") {
                    let response = format!("hello, {planet}");
                    conn.ok(response)
                } else {
                    conn
                }
            }),
    ))
}