use std::path::PathBuf;
use salvo_core::fs::{NamedFile, NamedFileBuilder};
use salvo_core::http::{Request, Response, StatusError};
use salvo_core::{async_trait, Depot, FlowCtrl, Handler, Writer};
#[derive(Clone)]
pub struct StaticFile(NamedFileBuilder);
impl StaticFile {
#[inline]
pub fn new(path: impl Into<PathBuf>) -> Self {
StaticFile(NamedFile::builder(path))
}
#[inline]
pub fn chunk_size(self, size: u64) -> Self {
Self(self.0.buffer_size(size))
}
}
#[async_trait]
impl Handler for StaticFile {
#[inline]
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.render(StatusError::not_found());
}
}
ctrl.skip_rest();
}
}