Skip to main content

sword_layers/servedir/
layer.rs

1use super::ServeDirConfig;
2use tower_http::services::{ServeDir, ServeFile};
3
4/// ### Serve Directory Layer
5///
6/// This struct represents the Serve Directory Layer which
7/// serves static files and directories.
8///
9/// The layer is a wrapper around `tower_http::services::ServeDir`.
10/// Serves static content with optional compression and custom chunk sizing.
11pub struct ServeDirLayer;
12
13impl ServeDirLayer {
14    pub fn new(config: &ServeDirConfig) -> ServeDir<ServeFile> {
15        let mut fallback = ServeFile::new(format!("{}/404.html", config.static_dir));
16
17        if let Some(not_found_file) = &config.not_found_file {
18            fallback = ServeFile::new(format!("{}/{not_found_file}", config.static_dir));
19        }
20
21        let mut layer = ServeDir::new(&config.static_dir).fallback(fallback);
22
23        if let Some(algorithm) = &config.compression_algorithm {
24            match algorithm.as_str() {
25                "br" => {
26                    layer = layer.precompressed_br();
27                }
28                "gzip" => {
29                    layer = layer.precompressed_gzip();
30                }
31                "deflate" => {
32                    layer = layer.precompressed_deflate();
33                }
34                "zstd" => {
35                    layer = layer.precompressed_zstd();
36                }
37                _ => {}
38            }
39        }
40
41        if let Some(chunk_size) = &config.chunk_size {
42            layer = layer.with_buf_chunk_size(chunk_size.parsed);
43        }
44
45        layer
46    }
47}