Skip to main content

basic/
serve_static.rs

1use afire::{extension, Header, Middleware, Response, Server, Status};
2
3use crate::Example;
4
5// Serve static files from a directory
6// afire middleware makes this *easy*
7pub struct ServeStatic;
8
9const STATIC_DIR: &str = "examples/basic/data";
10const STATIC_PATH: &str = "/";
11
12impl Example for ServeStatic {
13    fn name(&self) -> &'static str {
14        "serve_static"
15    }
16
17    fn exec(&self) {
18        // Create a new Server instance on localhost port 8080
19        let mut server = Server::<()>::new("localhost", 8080);
20
21        // Make a new static file server with a path
22        extension::ServeStatic::new(STATIC_DIR)
23            // The middleware priority is by most recently defined.
24            // The middleware function takes 3 parameters: the request, the response, and weather the file was loaded successfully.
25            // In your middleware you can modify the response and the bool.
26            .middleware(|req, res, _suc| {
27                // Print path served
28                println!("Served: {}", req.path);
29                // Return none to not mess with response
30                // Or in this case add a header and pass through the success value
31                res.headers.push(Header::new("X-Static", "true"));
32            })
33            // Function that runs when no file is found to serve
34            // This will run before middleware
35            .not_found(|_req, _dis| {
36                Response::new()
37                    .status(Status::NotFound)
38                    .text("Page Not Found!")
39            })
40            // Add an extra mime type to the server
41            // It has a lot already
42            .mime_type("key", "value")
43            // Set serve path
44            .path(STATIC_PATH)
45            // Attach the middleware to the server
46            .attach(&mut server);
47
48        // View the file at http://localhost:8080
49        // You should also see a favicon in the browser tab
50
51        // Start the server
52        // This will block the current thread
53        server.start().unwrap();
54    }
55}