Skip to content

Commit

Permalink
return NotModified if resource has not been modified.
Browse files Browse the repository at this point in the history
  • Loading branch information
hcldan committed Mar 11, 2024
1 parent 84ece56 commit 0cfaa21
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions core/lib/src/fs/server_file.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::io;

use crate::http::hyper::header::IF_MODIFIED_SINCE;
use rocket_http::Status;
use time::OffsetDateTime;

use crate::fs::MaybeCompressedFile;
Expand All @@ -12,7 +14,7 @@ use crate::Request;
/// [`FileServer`]: crate::fs::FileServer
#[derive(Debug)]
pub(crate) struct ServerFile {
last_modified: Option<String>,
last_modified: Option<OffsetDateTime>,
file: MaybeCompressedFile,
}

Expand All @@ -28,8 +30,8 @@ impl ServerFile {
let metadata = file.file().metadata().await?;
let last_modified = metadata.modified()?.duration_since(std::time::UNIX_EPOCH).ok()
.and_then(|d| i64::try_from(d.as_secs()).ok())
.and_then(|sec| OffsetDateTime::from_unix_timestamp(sec).ok())
.and_then(|odt| odt.format(&time::format_description::well_known::Rfc2822).ok());
.and_then(|sec| OffsetDateTime::from_unix_timestamp(sec).ok());
// .and_then(|odt| odt.format(&time::format_description::well_known::Rfc2822).ok());

Ok(Self { last_modified, file })
}
Expand All @@ -38,12 +40,21 @@ impl ServerFile {
/// Sets the last-modified data for the file response
impl<'r> Responder<'r, 'static> for ServerFile {
fn respond_to(self, request: &'r Request<'_>) -> response::Result<'static> {
let mut response = self.file.respond_to(request)?;
let if_modified_since = request.headers().get_one(IF_MODIFIED_SINCE.as_str())
.and_then(|v| time::OffsetDateTime::parse(v, &time::format_description::well_known::Rfc2822).ok());

if let Some(last_modified) = self.last_modified {
response.set_raw_header("last-modified", last_modified);
match (self.last_modified, if_modified_since) {
(Some(lm), Some(ims)) if lm <= ims =>
return crate::Response::build().status(Status::NotModified).ok(),
_ => {}
}

let mut response = self.file.respond_to(request)?;

self.last_modified
.and_then(|odt| odt.format(&time::format_description::well_known::Rfc2822).ok())
.map(|lm| response.set_raw_header("last-modified", lm));

Ok(response)
}
}

0 comments on commit 0cfaa21

Please sign in to comment.