index : static-web-server.git

ascending towards madness

author Matias Fontanini <matias.fontanini@gmail.com> 2023-02-22 6:46:12.0 +00:00:00
committer GitHub <noreply@github.com> 2023-02-22 6:46:12.0 +00:00:00
commit
b2cff1b1661b071617a021a21ddc2b6c9481c5dc [patch]
tree
6e70a608bcb92ca15395f06baa1b34623e557fe7
parent
40a532e76536e73252c4553e7ea20b73c3575f05
download
b2cff1b1661b071617a021a21ddc2b6c9481c5dc.tar.gz

refactor: optimize cache control headers file type detection (#175)



Diff

 src/control_headers.rs | 34 ++++++++++++++++++++++------------
 1 file changed, 22 insertions(+), 12 deletions(-)

diff --git a/src/control_headers.rs b/src/control_headers.rs
index cdd6a4b..9b1adef 100644
--- a/src/control_headers.rs
+++ b/src/control_headers.rs
@@ -21,16 +21,12 @@ pub fn append_headers(uri: &str, resp: &mut Response<Body>) {
    // Default max-age value in seconds (one day)
    let mut max_age = MAX_AGE_ONE_DAY;

    if CACHE_EXT_ONE_HOUR
        .iter()
        .any(|x| uri.ends_with(&[".", *x].concat()))
    {
        max_age = MAX_AGE_ONE_HOUR;
    } else if CACHE_EXT_ONE_YEAR
        .iter()
        .any(|x| uri.ends_with(&[".", *x].concat()))
    {
        max_age = MAX_AGE_ONE_YEAR;
    if let Some(extension) = uri_file_extension(uri) {
        if CACHE_EXT_ONE_HOUR.binary_search(&extension).is_ok() {
            max_age = MAX_AGE_ONE_HOUR;
        } else if CACHE_EXT_ONE_YEAR.binary_search(&extension).is_ok() {
            max_age = MAX_AGE_ONE_YEAR;
        }
    }

    let cache_control = CacheControl::new()
@@ -44,13 +40,20 @@ fn duration_from_secs(secs: u64) -> std::time::Duration {
    std::time::Duration::from_secs(std::cmp::min(secs, u32::MAX as u64))
}

/// Gets the file extension for a URI.
///
/// This assumes the extension contains a single dot. e.g. for "/file.tar.gz" it returns "gz".
fn uri_file_extension(uri: &str) -> Option<&str> {
    uri.rsplit_once('.').map(|(_, rest)| rest)
}

#[cfg(test)]
mod tests {
    use hyper::{Body, Response, StatusCode};

    use super::{
        append_headers, CACHE_EXT_ONE_HOUR, CACHE_EXT_ONE_YEAR, MAX_AGE_ONE_DAY, MAX_AGE_ONE_HOUR,
        MAX_AGE_ONE_YEAR,
        append_headers, uri_file_extension, CACHE_EXT_ONE_HOUR, CACHE_EXT_ONE_YEAR,
        MAX_AGE_ONE_DAY, MAX_AGE_ONE_HOUR, MAX_AGE_ONE_YEAR,
    };

    #[tokio::test]
@@ -101,4 +104,11 @@ mod tests {
            );
        }
    }

    #[test]
    fn find_uri_extension() {
        assert_eq!(uri_file_extension("/potato.zip"), Some("zip"));
        assert_eq!(uri_file_extension("/potato."), Some(""));
        assert_eq!(uri_file_extension("/"), None);
    }
}