1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use std::path::PathBuf;
use salvo_core::async_trait;
use salvo_core::fs::{NamedFile, NamedFileBuilder};
use salvo_core::http::errors::StatusError;
use salvo_core::routing::FlowCtrl;
use salvo_core::Handler;
use salvo_core::{Depot, Request, Response, Writer};
#[derive(Clone)]
pub struct FileHandler(NamedFileBuilder);
impl FileHandler {
pub fn new(path: impl Into<PathBuf>) -> Self {
FileHandler(NamedFile::builder(path))
}
pub fn chunk_size(self, size: u64) -> Self {
Self(self.0.with_buffer_size(size))
}
}
#[async_trait]
impl Handler for FileHandler {
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
match self.0.clone().build().await {
Ok(file) => file.write(req, depot, res).await,
Err(_) => {
res.set_status_error(StatusError::not_found());
}
}
ctrl.skip_rest();
}
}