diff --git a/crates/core/src/writing/mod.rs b/crates/core/src/writing/mod.rs index 4dd31d2a9..5b50c38ac 100644 --- a/crates/core/src/writing/mod.rs +++ b/crates/core/src/writing/mod.rs @@ -43,6 +43,22 @@ where } } +#[async_trait] +impl

Writer for Option

+where + P: Piece + Sized + Send, +{ + #[inline] + async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) { + match self { + Some(v) => v.render(res), + None => { + res.status_code(StatusCode::NOT_FOUND); + } + } + } +} + #[async_trait] impl Writer for Result where diff --git a/crates/serve-static/src/embed.rs b/crates/serve-static/src/embed.rs index 021898a74..c754c6233 100644 --- a/crates/serve-static/src/embed.rs +++ b/crates/serve-static/src/embed.rs @@ -56,6 +56,9 @@ fn render_embedded_data( res: &mut Response, mime: Option, ) { + let mime = mime.unwrap_or_else(|| mime_guess::from_path(req.uri().path()).first_or_octet_stream()); + res.headers_mut().insert(CONTENT_TYPE, mime.as_ref().parse().unwrap()); + let hash = hex::encode(metadata.sha256_hash()); // if etag is matched, return 304 if req @@ -71,8 +74,6 @@ fn render_embedded_data( // otherwise, return 200 with etag hash res.headers_mut().insert(ETAG, hash.parse().unwrap()); - let mime = mime.unwrap_or_else(|| mime_guess::from_path(req.uri().path()).first_or_octet_stream()); - res.headers_mut().insert(CONTENT_TYPE, mime.as_ref().parse().unwrap()); match data { Cow::Borrowed(data) => { res.write_body(data).ok(); diff --git a/examples/static-embed-file/src/main.rs b/examples/static-embed-file/src/main.rs index 57a3dba06..76ddfc87a 100644 --- a/examples/static-embed-file/src/main.rs +++ b/examples/static-embed-file/src/main.rs @@ -21,5 +21,7 @@ async fn serve_file(req: &mut Request, res: &mut Response) { let path = req.param::("**path").unwrap(); if let Some(file) = Assets::get(&path) { file.render(req, res); + } else { + res.status_code(StatusCode::NOT_FOUND); } }