basic/
basic.rs

1use afire::{Content, HeaderType, Method, Response, Server, Status};
2
3use crate::Example;
4
5// You can run this example with `cargo run --example basic -- basic`
6
7// In this example we will create a basic server that responds to GET requests to "/" with a simple text response
8// Note: the only code here you need to worry about is the code in the exec method
9
10pub struct Basic;
11
12impl Example for Basic {
13    fn name(&self) -> &'static str {
14        "basic"
15    }
16
17    fn exec(&self) {
18        // Create a new Server instance on localhost port 8080
19        // The type parameter is for a server wide state, which we don't need yet so we use ()
20        // In this example we are setting the ip with a string, but you can also use a Ipv4Addr or [u8; 4]
21        let mut server = Server::<()>::new("localhost", 8080);
22
23        // Define a handler for GET "/"
24        server.route(Method::GET, "/", |_req| {
25            Response::new()
26                // By default the status is 200 (OK)
27                // You can also define it yourself with the status method
28                .status(Status::Ok)
29                // By default the reason phrase is derived from the status
30                // But you can also define it yourself with the reason method
31                .reason("OK!")
32                // Although is is named `text` it takes any type that implements Display
33                // So for example numbers, or a serde_json::Value will work
34                .text("Hi :P")
35                // You can also add headers
36                // The header method will take a HeaderType, String, or &str and the value can be a String or &str
37                // (this is not the proper way to use the Date header, but it works for this example)
38                .header(HeaderType::Date, "today")
39                // Now we will set the content type to text/plain; charset=utf-8
40                // The content method just adds a Content-Type header
41                .content(Content::TXT)
42        });
43
44        // Start the server in single threaded mode
45        // This will block the current thread
46        server.start().unwrap();
47
48        // Now navigate to http://localhost:8080 in your browser
49        // You should see "Hi :P"
50    }
51}