phoenix_view/
static_files.rs1use std::{
2 fs,
3 path::{Path, PathBuf},
4 sync::Arc,
5};
6
7use phoenix_http::{
8 BoxFuture, Bytes, HeaderValue, Middleware, Next, Request, Response, StatusCode, header,
9};
10
11use crate::assets::AssetManifest;
12
13#[derive(Clone, Debug)]
19pub struct ServeProductionAssets {
20 assets: Arc<AssetManifest>,
21 root: PathBuf,
22}
23
24impl ServeProductionAssets {
25 #[must_use]
26 pub fn new(assets: AssetManifest, root: impl Into<PathBuf>) -> Self {
27 Self {
28 assets: Arc::new(assets),
29 root: root.into(),
30 }
31 }
32}
33
34impl Middleware for ServeProductionAssets {
35 fn handle(&self, request: Request, next: Next) -> BoxFuture<Response> {
36 let assets = Arc::clone(&self.assets);
37 let root = self.root.clone();
38 Box::pin(async move {
39 let path = request.uri().path();
40 if !path.starts_with(assets.public_path.as_str()) {
41 return next.run(request).await;
42 }
43 match assets.resolve_static(&root, path) {
44 Ok(file) => file_response(&file),
45 Err(_) => Response::text("Not Found").with_status(StatusCode::NOT_FOUND),
46 }
47 })
48 }
49}
50
51fn file_response(path: &Path) -> Response {
52 let Ok(bytes) = fs::read(path) else {
53 return Response::text("Not Found").with_status(StatusCode::NOT_FOUND);
54 };
55 let mut response = Response::new(StatusCode::OK, Bytes::from(bytes));
56 if let Some(content_type) = content_type_for(path)
57 && let Ok(value) = HeaderValue::from_str(content_type)
58 {
59 response.headers_mut().insert(header::CONTENT_TYPE, value);
60 }
61 response.headers_mut().insert(
62 header::CACHE_CONTROL,
63 HeaderValue::from_static("public, max-age=31536000, immutable"),
64 );
65 response
66}
67
68fn content_type_for(path: &Path) -> Option<&'static str> {
69 match path.extension().and_then(|value| value.to_str())? {
70 "js" | "mjs" => Some("text/javascript; charset=utf-8"),
71 "css" => Some("text/css; charset=utf-8"),
72 "json" => Some("application/json; charset=utf-8"),
73 "map" => Some("application/json; charset=utf-8"),
74 "svg" => Some("image/svg+xml"),
75 "png" => Some("image/png"),
76 "jpg" | "jpeg" => Some("image/jpeg"),
77 "webp" => Some("image/webp"),
78 "woff2" => Some("font/woff2"),
79 "woff" => Some("font/woff"),
80 _ => None,
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn javascript_content_type() {
90 assert_eq!(
91 content_type_for(Path::new("phoenix-abc.js")),
92 Some("text/javascript; charset=utf-8")
93 );
94 assert_eq!(
95 content_type_for(Path::new("client.css")),
96 Some("text/css; charset=utf-8")
97 );
98 }
99}