basic/routing.rs
1use afire::{Content, Method, Response, Server, Status};
2
3use crate::Example;
4
5// You can run this example with `cargo run --example basic -- routing`
6
7// In this example I will introduce the way routing works in afire
8// In afire the newest routes take priority over other routes.
9// This means that if you have two routes that could run for a request
10// the one defined last will run.
11
12// To explain this better I will label the routes with numbers to represent their priority.
13// Higher priority numbers will run first
14// Note: In the afire backend code there is no priority number its just the order in which they are defined
15pub struct Routing;
16
17impl Example for Routing {
18 fn name(&self) -> &'static str {
19 "routing"
20 }
21
22 fn exec(&self) {
23 // Create a new Server instance on localhost port 8080
24 let mut server: Server = Server::<()>::new("localhost", 8080);
25
26 // Define 404 page
27 // This route will run for all requests but because any other route
28 // will take priority it will only run when no other route is defined.
29 /* PRIO 0 */
30 server.route(Method::ANY, "**", |_req| {
31 Response::new()
32 .status(Status::NotFound)
33 .text("The page you are looking for does not exist :/")
34 .content(Content::TXT)
35 });
36
37 // Define a route
38 // As this is defined last, it will take a higher priority
39 /* PRIO 1 */
40 server.route(Method::GET, "/", |_req| {
41 Response::new().text("Hello World!").content(Content::TXT)
42 });
43
44 // Now goto http://localhost:8080/ and you should see "Hello World"
45 // But if you go to http://localhost:8080/somthing-else you should see the 404 page
46
47 // Start the server
48 // This will block the current thread
49 server.start().unwrap();
50 }
51}