Skip to main content

phoenix_view/
static_files.rs

1use 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/// Serve Vite production assets declared by [`AssetManifest`].
14///
15/// Requests whose path starts with the manifest `public_path` (default `/assets/`)
16/// are resolved through the manifest and read from `root` (typically `public/assets`).
17/// All other requests continue down the middleware stack.
18#[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" | "map" => Some("application/json; charset=utf-8"),
73        "svg" => Some("image/svg+xml"),
74        "png" => Some("image/png"),
75        "jpg" | "jpeg" => Some("image/jpeg"),
76        "webp" => Some("image/webp"),
77        "woff2" => Some("font/woff2"),
78        "woff" => Some("font/woff"),
79        _ => None,
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn javascript_content_type() {
89        assert_eq!(
90            content_type_for(Path::new("phoenix-abc.js")),
91            Some("text/javascript; charset=utf-8")
92        );
93        assert_eq!(
94            content_type_for(Path::new("client.css")),
95            Some("text/css; charset=utf-8")
96        );
97    }
98}