small_router_context/
small-router-context.rs

1/*
2 * Copyright (c) 2025 Bastiaan van der Plaat
3 *
4 * SPDX-License-Identifier: MIT
5 */
6
7//! A simple small-router example with context
8
9use std::net::{Ipv4Addr, TcpListener};
10
11use small_http::{Request, Response, Status};
12use small_router::RouterBuilder;
13
14#[derive(Clone)]
15struct Context {
16    data: String,
17}
18
19fn home(_req: &Request, ctx: &Context) -> Response {
20    println!("{}", ctx.data);
21    Response::with_body("Home")
22}
23
24fn about(_req: &Request, ctx: &Context) -> Response {
25    println!("{}", ctx.data);
26    Response::with_body("About")
27}
28
29fn not_found(_req: &Request, _ctx: &Context) -> Response {
30    Response::with_status(Status::NotFound).body("404 Not Found")
31}
32
33fn main() {
34    let ctx = Context {
35        data: "Data".to_string(),
36    };
37    let router = RouterBuilder::with(ctx)
38        .get("/", home)
39        .get("/about", about)
40        .fallback(not_found)
41        .build();
42
43    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080))
44        .unwrap_or_else(|_| panic!("Can't bind to port"));
45    small_http::serve(listener, move |req| router.handle(req));
46}