From d0c5e0a59fd43d639fb6359a4696b17b5d17716d Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Thu, 21 Sep 2023 00:00:09 -0400 Subject: [PATCH] Attempt to add etag caching --- file-service/src/main.rs | 49 +++++++++++++++++++++------------------ file-service/src/pages.rs | 2 +- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/file-service/src/main.rs b/file-service/src/main.rs index f15d2a0..7410ca8 100644 --- a/file-service/src/main.rs +++ b/file-service/src/main.rs @@ -247,12 +247,6 @@ pub async fn main() { "get-file", ); - router.get( - "/:id/tn", - files::GetThumbnailHandler { app: app.clone() }, - "get-thumbnail", - ); - router.post("/", files::PostHandler { app: app.clone() }, "upload-file"); router.delete( @@ -299,24 +293,35 @@ pub async fn main() { } }); - let thumbnail = warp::path!(String / "tn").map({ - let app = app.clone(); - move |id: String| { - let mut content = Vec::new(); - match app.read().unwrap().get_thumbnail(&id) { - Ok((info, mut stream)) => { - let _ = stream.read_to_end(&mut content); - warp::http::Response::builder() - .header("content-type", info.file_type) - .status(StatusCode::OK) - .body(content) + let thumbnail = warp::path!(String / "tn") + .and(warp::header::optional::("if-none-match")) + .map({ + let app = app.clone(); + move |id: String, old_etags: Option| { + let mut content = Vec::new(); + match app.read().unwrap().get_thumbnail(&id) { + Ok((info, mut stream)) => match old_etags { + Some(old_etags) if old_etags != info.hash => { + warp::http::Response::builder() + .header("content-type", info.file_type) + .status(StatusCode::NOT_MODIFIED) + .body(content) + } + _ => { + let _ = stream.read_to_end(&mut content); + warp::http::Response::builder() + .header("content-type", info.file_type) + .header("etag", info.hash) + .status(StatusCode::OK) + .body(content) + } + }, + Err(_err) => warp::http::Response::builder() + .status(StatusCode::NOT_FOUND) + .body(content), } - Err(_err) => warp::http::Response::builder() - .status(StatusCode::NOT_FOUND) - .body(content), } - } - }); + }); let server = warp::serve(root.or(thumbnail)); server diff --git a/file-service/src/pages.rs b/file-service/src/pages.rs index 3f61170..12a92e1 100644 --- a/file-service/src/pages.rs +++ b/file-service/src/pages.rs @@ -25,7 +25,7 @@ pub fn index(files: Vec>) -> build_html::HtmlPage { let tn = Container::new(ContainerType::Div) .with_attributes(vec![("class", "thumbnail")]) .with_link( - format!("/file/{}", file.info().id), + format!("/{}", file.info().id), Image::new(&format!("{}/tn", file.info().id)).to_html_string(), ); container.add_html(tn);