Skip to main content

basic/
data.rs

1use std::net::Ipv4Addr;
2
3use afire::{Content, HeaderType, Method, Query, Response, Server};
4
5use crate::Example;
6
7// You can run this example with `cargo run --example basic -- data`
8
9// In this example we will work with data in the request using query params and form data
10
11pub struct Data;
12
13impl Example for Data {
14    fn name(&self) -> &'static str {
15        "data"
16    }
17
18    fn exec(&self) {
19        // Create a new Server instance on localhost port 8080
20        let mut server = Server::<()>::new(Ipv4Addr::LOCALHOST, 8080);
21
22        // Define a route to handel query string
23        // This will try to find a name value pair in the query string
24        server.route(Method::GET, "/", |req| {
25            // Format the response text
26            let text = format!(
27                "<h1>Hello, {}!</h1>",
28                // Get the query value of name and default to "Nobody" if not found
29                req.query.get("name").unwrap_or("Nobody")
30            );
31
32            Response::new().text(text).content(Content::HTML)
33        });
34
35        // Define another route
36        // This time to handle form data
37        server.route(Method::POST, "/form", |req| {
38            // The body of requests is not part of the req.query
39            // Instead it is part of the req.body but as a string
40            // We will need to parse it get it as a query
41            let body_data = Query::from_body(&String::from_utf8_lossy(&req.body));
42
43            let name = body_data.get("name").unwrap_or("Nobody");
44            let text = format!("<h1>Hello, {}</h1>", name);
45
46            // Create a new response, with the following default data
47            // - Status: 200
48            // - Data: OK
49            // - Headers: []
50            Response::new()
51                // Set the response body to be text
52                .text(text)
53                // Set the `Content-Type` header to be `text/html`
54                // Note: This could also be set with the Response::content method
55                .header(HeaderType::ContentType, "text/html")
56        });
57
58        // Define webpage with form
59        // The form data will be post to /form on submit
60        server.route(Method::GET, "/form", |_req| {
61            let page = r#"<form method="post">
62            <label for="name">Name:</label>
63            <input type="text" id="name" name="name"><br><br>
64            <input type="submit" value="Submit">
65      </form>"#;
66
67            Response::new().text(page).content(Content::HTML)
68        });
69
70        // Define a page with path params
71        server.route(Method::GET, "/greet/{name}", |req| {
72            // As this route would ever run without all the path params being filled
73            // It is safe to unwrap if the name is in the path
74            let data = format!("<h1>Hello, {}</h1>", req.param("name").unwrap());
75
76            Response::new().text(data).content(Content::HTML)
77        });
78
79        // You can now goto http://localhost:8080?name=John and should see "Hello, John"
80        // If you goto http://localhost:8080/form and submit the form you should see "Hello, {NAME}"
81        // Also goto http://localhost:8080/greet/John and you should see "Hello, John"
82
83        // Start the server
84        // This will block the current thread
85        server.start().unwrap();
86    }
87}