Attempt to add etag caching

This commit is contained in:
Savanni D'Gerinel 2023-09-21 00:00:09 -04:00
parent f4b3e811fc
commit 1bb6bd78e6
2 changed files with 28 additions and 23 deletions

View File

@ -247,12 +247,6 @@ pub async fn main() {
"get-file", "get-file",
); );
router.get(
"/:id/tn",
files::GetThumbnailHandler { app: app.clone() },
"get-thumbnail",
);
router.post("/", files::PostHandler { app: app.clone() }, "upload-file"); router.post("/", files::PostHandler { app: app.clone() }, "upload-file");
router.delete( router.delete(
@ -299,18 +293,29 @@ pub async fn main() {
} }
}); });
let thumbnail = warp::path!(String / "tn").map({ let thumbnail = warp::path!(String / "tn")
.and(warp::header::optional::<String>("if-none-match"))
.map({
let app = app.clone(); let app = app.clone();
move |id: String| { move |id: String, old_etags: Option<String>| {
let mut content = Vec::new(); let mut content = Vec::new();
match app.read().unwrap().get_thumbnail(&id) { match app.read().unwrap().get_thumbnail(&id) {
Ok((info, mut stream)) => { 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); let _ = stream.read_to_end(&mut content);
warp::http::Response::builder() warp::http::Response::builder()
.header("content-type", info.file_type) .header("content-type", info.file_type)
.header("etag", info.hash)
.status(StatusCode::OK) .status(StatusCode::OK)
.body(content) .body(content)
} }
},
Err(_err) => warp::http::Response::builder() Err(_err) => warp::http::Response::builder()
.status(StatusCode::NOT_FOUND) .status(StatusCode::NOT_FOUND)
.body(content), .body(content),

View File

@ -25,7 +25,7 @@ pub fn index(files: Vec<Result<File, FileError>>) -> build_html::HtmlPage {
let tn = Container::new(ContainerType::Div) let tn = Container::new(ContainerType::Div)
.with_attributes(vec![("class", "thumbnail")]) .with_attributes(vec![("class", "thumbnail")])
.with_link( .with_link(
format!("/file/{}", file.info().id), format!("/{}", file.info().id),
Image::new(&format!("{}/tn", file.info().id)).to_html_string(), Image::new(&format!("{}/tn", file.info().id)).to_html_string(),
); );
container.add_html(tn); container.add_html(tn);