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",
);
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::<String>("if-none-match"))
.map({
let app = app.clone();
move |id: String, old_etags: Option<String>| {
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

View File

@ -25,7 +25,7 @@ pub fn index(files: Vec<Result<File, FileError>>) -> 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);