use std::path::PathBuf;
use salvo_core::fs::{NamedFile, NamedFileBuilder};
use salvo_core::http::{Method, Request, Response, StatusError};
use salvo_core::{Depot, FlowCtrl, Handler, async_trait};
#[derive(Clone, Debug)]
pub struct StaticFile(NamedFileBuilder);
impl StaticFile {
#[inline]
pub fn new(path: impl Into<PathBuf>) -> Self {
Self(NamedFile::builder(path))
}
#[inline]
#[must_use]
pub fn chunk_size(self, size: u64) -> Self {
Self(self.0.buffer_size(size))
}
#[inline]
#[must_use]
pub fn preload_threshold(self, threshold: u64) -> Self {
Self(self.0.preload_threshold(threshold))
}
#[inline]
#[must_use]
pub fn disposition_type(self, disposition_type: impl Into<String>) -> Self {
Self(self.0.disposition_type(disposition_type))
}
#[inline]
#[must_use]
pub fn attached_name(self, name: impl Into<String>) -> Self {
Self(self.0.attached_name(name))
}
#[inline]
#[must_use]
pub fn use_content_type_options(self, value: bool) -> Self {
Self(self.0.use_content_type_options(value))
}
}
#[async_trait]
impl Handler for StaticFile {
#[inline]
async fn handle(
&self,
req: &mut Request,
_depot: &mut Depot,
res: &mut Response,
ctrl: &mut FlowCtrl,
) {
let mut builder = self.0.clone();
if req.method() == Method::HEAD {
builder = builder.preload_threshold(0);
}
match builder.build().await {
Ok(file) => {
file.send_with_method(req.method(), req.headers(), res)
.await
}
Err(_) => {
res.render(StatusError::not_found());
}
}
ctrl.skip_rest();
}
}