oak_http_server/
handlers.rs

1//! Includes various handlers provided by the library
2
3use std::fs;
4
5use crate::{Request, Response};
6
7fn read_file(parent_dir: String, request: Request, mut response: Response) {
8    match fs::read_to_string(
9        parent_dir.chars().skip(1).collect::<String>() + &request.target.relative_path,
10    ) {
11        Ok(contents) => response.send(contents),
12        Err(error) => {
13            use crate::enums::Status;
14            use std::io::ErrorKind;
15
16            let status: Status = match error.kind() {
17                ErrorKind::NotFound => Status::NotFound,
18                _ => Status::InternalError,
19            };
20
21            response.status(status);
22            response.end();
23        }
24    }
25}
26
27/// Read a file from the same directory as the one specified during the handler's creation
28///
29/// # Example:
30///
31/// ```
32/// use oak_http_server::{handlers::read_same_dir, Server};
33///
34/// fn main() {
35///	    let hostname = "localhost";
36///     let port: u16 = 2300;
37///
38///     let mut server = Server::new(hostname, port);
39///		// If the server were to be started, any content the server would provide for the `/www` directory would be readen from the local `www` directory
40///     server.on_directory("/www", read_same_dir);
41/// }
42/// ```
43pub fn read_same_dir(request: Request, response: Response) {
44    read_file(request.target.target_path.clone(), request, response)
45}
46
47/// Read a file from the directory different than the one specified during the handler's creation
48///
49/// # Example:
50///
51/// ```
52/// use oak_http_server::{handlers::read_diff_dir, Server};
53///
54/// fn main() {
55///	    let hostname = "localhost";
56///     let port: u16 = 2300;
57///
58///     let mut server = Server::new(hostname, port);
59///		// If the server were to be started, any content the server would provide for the `/www` directory would be readen from the local `etc` directory
60///     server.on_directory("/www", read_diff_dir("etc"));
61/// }
62/// ```
63
64pub fn read_diff_dir<S>(parent_dir: S) -> impl Fn(Request, Response)
65where
66    S: Into<String> + Clone,
67{
68    move |request: Request, response: Response| {
69        read_file(parent_dir.clone().into(), request, response)
70    }
71}