From: Geoffrey Allott Date: Tue, 23 Mar 2021 22:58:19 +0000 (+0000) Subject: set cache-control headers for static content X-Git-Url: https://git.pointlesshacks.com/?a=commitdiff_plain;h=a2bae77db192bdd926c91ae115934cf601672bbd;p=pokerwave.git set cache-control headers for static content --- diff --git a/src/main.rs b/src/main.rs index c4f4e96..b18f350 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 { } } +async fn append_cache_control(mut response: Response) -> Result { + 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>>> = 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));