basic/path_prams.rs
1use afire::{Content, Method, Response, Server};
2
3use crate::Example;
4
5// You can run this example with `cargo run --example basic -- path_params`
6
7// Use Path params to send data through a route path
8// You can also add `*` segments to match with any text
9pub struct PathParam;
10
11impl Example for PathParam {
12 fn name(&self) -> &'static str {
13 "path_params"
14 }
15
16 fn exec(&self) {
17 // Create a new Server instance on localhost port 8080
18 let mut server: Server = Server::<()>::new("localhost", 8081);
19
20 // Define a handler for GET "/greet/{name}"
21 // This will handel requests with anything where the {name} is
22 // This includes "/greet/bob", "/greet/fin"
23 server.route(Method::GET, "/greet/{name}", |req| {
24 // Get name path param
25 let name = req.param("name").unwrap();
26
27 // Make a nice Message to send
28 let message = format!("Hello, {}", name);
29
30 // Send Response
31 Response::new().text(message).content(Content::TXT)
32 });
33
34 // Define a greet route for Darren because he is very cool
35 // This will take priority over the other route as it is defined after
36 server.route(Method::GET, "/greet/Darren/", |_req| {
37 Response::new().text("Hello, Darren. You are very cool")
38 });
39
40 // Start the server
41 // This will block the current thread
42 server.start().unwrap();
43 }
44}