[pbs-devel] [PATCH proxmox-backup 3/6] server/rest: set last-modified for static files

Dominik Csapak d.csapak at proxmox.com
Fri Nov 6 11:03:40 CET 2020


this way the browser can cache them

Signed-off-by: Dominik Csapak <d.csapak at proxmox.com>
---
 src/server/rest.rs | 23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)

diff --git a/src/server/rest.rs b/src/server/rest.rs
index ea87c9c8..d0169ba5 100644
--- a/src/server/rest.rs
+++ b/src/server/rest.rs
@@ -492,10 +492,17 @@ async fn simple_static_file_download(filename: PathBuf) -> Result<Response<Body>
 
     use tokio::io::AsyncReadExt;
 
-    let mut file = File::open(filename)
+    let mut file = File::open(&filename)
         .await
         .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
 
+    let mtime = crate::tools::fs::get_async_file_mtime(filename)
+        .await
+        .map_err(|err| http_err!(INTERNAL_SERVER_ERROR, "File stat failed: {}", err))?;
+
+    let last_modified = proxmox::tools::time::strftime_utc("%a, %d %b %Y %T GMT", mtime)
+        .map_err(|err| http_err!(INTERNAL_SERVER_ERROR, "strftime failed: {}", err))?;
+
     let mut data: Vec<u8> = Vec::new();
     file.read_to_end(&mut data)
         .await
@@ -505,16 +512,27 @@ async fn simple_static_file_download(filename: PathBuf) -> Result<Response<Body>
     response.headers_mut().insert(
         header::CONTENT_TYPE,
         header::HeaderValue::from_static(content_type));
+    response.headers_mut().insert(
+        header::LAST_MODIFIED,
+        header::HeaderValue::from_str(&last_modified)?);
     Ok(response)
 }
 
 async fn chuncked_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> {
     let (content_type, _nocomp) = extension_to_content_type(&filename);
 
-    let file = File::open(filename)
+    let file = File::open(&filename)
         .await
         .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
 
+    let mtime = crate::tools::fs::get_async_file_mtime(filename)
+        .await
+        .map_err(|err| http_err!(INTERNAL_SERVER_ERROR, "File stat failed: {}", err))?;
+
+    let last_modified = proxmox::tools::time::strftime_utc("%a, %d %b %Y %T GMT", mtime)
+        .map_err(|err| http_err!(INTERNAL_SERVER_ERROR, "strftime failed: {}", err))?;
+
+
     let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
         .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze()));
     let body = Body::wrap_stream(payload);
@@ -523,6 +541,7 @@ async fn chuncked_static_file_download(filename: PathBuf) -> Result<Response<Bod
     Ok(Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, content_type)
+       .header(header::LAST_MODIFIED, &last_modified)
        .body(body)
        .unwrap()
     )
-- 
2.20.1






More information about the pbs-devel mailing list