small_router_simple/
small-router-simple.rs1use std::net::{Ipv4Addr, TcpListener};
10
11use small_http::{Request, Response, Status};
12use small_router::RouterBuilder;
13
14fn home(_req: &Request, _ctx: &()) -> Response {
15 Response::with_body("Home")
16}
17
18fn hello(_req: &Request, _ctx: &()) -> Response {
19 Response::with_body(format!(
20 "Hello, {}!",
21 _req.params.get("name").unwrap_or(&"World".to_string())
22 ))
23}
24
25fn not_found(_req: &Request, _ctx: &()) -> Response {
26 Response::with_status(Status::NotFound).body("404 Not Found")
27}
28
29fn main() {
30 let router = RouterBuilder::with(())
31 .get("/", home)
32 .get("/hello/:name", hello)
33 .fallback(not_found)
34 .build();
35
36 let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080))
37 .unwrap_or_else(|_| panic!("Can't bind to port"));
38 small_http::serve(listener, move |req| router.handle(req));
39}