set cache-control headers for static content
authorGeoffrey Allott <geoffrey@allott.email>
Tue, 23 Mar 2021 22:58:19 +0000 (22:58 +0000)
committerGeoffrey Allott <geoffrey@allott.email>
Tue, 23 Mar 2021 22:58:19 +0000 (22:58 +0000)
src/main.rs

index c4f4e963c3d4bab0765a719a430a2f030234e738..b18f35032eecd5ed0ff144f9ae0cd786cb792f6f 100644 (file)
@@ -8,15 +8,17 @@ use std::fs::read_to_string;
 use std::future::Future;
 use std::path::Path;
 use std::pin::Pin;
+use std::time::Duration;
 
 use clap::{app_from_crate, crate_authors, crate_description, crate_name, crate_version, AppSettings, Arg, SubCommand};
 use futures::{channel::mpsc::channel, future::pending, select, FutureExt, StreamExt};
 use redis::Client;
 use signal_hook::consts::signal::*;
 use signal_hook_async_std::Signals;
-use tide::utils::After;
 use tide::{
     listener::{ConcurrentListener, ToListener},
+    http::{cache::{CacheControl, CacheDirective}, headers::CACHE_CONTROL},
+    utils::After,
     Body, Response, StatusCode,
 };
 use tide_rustls::TlsListener;
@@ -54,6 +56,17 @@ async fn serve_404(response: Response) -> Result<Response, tide::Error> {
     }
 }
 
+async fn append_cache_control(mut response: Response) -> Result<Response, tide::Error> {
+    if response.status() == StatusCode::Ok {
+        let mut cache_control = CacheControl::new();
+        cache_control.push(CacheDirective::Public);
+        cache_control.push(CacheDirective::MaxAge(Duration::from_secs(24 * 60 * 60)));
+        cache_control.push(CacheDirective::Immutable);
+        response.append_header(CACHE_CONTROL, cache_control);
+    }
+    Ok(response)
+}
+
 #[async_std::main]
 async fn main() -> Result<(), tide::Error> {
     let matches = app_from_crate!()
@@ -128,8 +141,8 @@ async fn main() -> Result<(), tide::Error> {
     let server: Pin<Box<dyn Future<Output = Result<(), std::io::Error>>>> = if run_server {
         let mut app = tide::with_state(server);
 
-        app.at("/").serve_dir(&config.server.site)?;
-        app.at("/").serve_file(config.server.site.join("index.html"))?;
+        app.at("/").with(After(append_cache_control)).serve_dir(&config.server.site)?;
+        app.at("/").with(After(append_cache_control)).serve_file(config.server.site.join("index.html"))?;
         app.at("/api").get(WebSocket::new(new_client));
         app.with(After(serve_404));