Skip to main content

basic/
serve_file.rs

1use afire::{Content, Method, Response, Server, Status};
2use std::fs::File;
3
4use crate::Example;
5
6// You can run this example with `cargo run --example basic -- serve_file`
7
8// Serve a local file
9// On each request, the server will read the file and send it to the client.
10// Usually it is preferred to use the ServeStatic middleware for this
11
12pub struct ServeFile;
13
14impl Example for ServeFile {
15    fn name(&self) -> &'static str {
16        "serve_file"
17    }
18
19    fn exec(&self) {
20        // Create a new Server instance on localhost port 8080
21        let mut server = Server::<()>::new("localhost", 8080);
22
23        // Define a handler for GET "/"
24        server.route(Method::GET, "/", |_req| {
25            // Try to open a file
26            match File::open("examples/basic/data/index.html") {
27                // If its found send it as response
28                // Because we used File::open and not fs::read, we can use the stream method to send the file in chunks
29                // This is more efficient than reading the whole file into memory and then sending it
30                Ok(content) => Response::new().stream(content).content(Content::HTML),
31
32                // If the file is not found, send a 404 response
33                Err(_) => Response::new()
34                    .status(Status::NotFound)
35                    .text("Not Found :/")
36                    .content(Content::TXT),
37            }
38        });
39
40        // View the file at http://localhost:8080
41
42        // Start the server
43        // This will block the current thread
44        server.start().unwrap();
45    }
46}