Skip to content

Commit

Permalink
feat: added static file caching in prod mode
Browse files Browse the repository at this point in the history
  • Loading branch information
johnbchron committed Feb 27, 2024
1 parent 17b14a8 commit 5812a5b
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions crates/site-server/src/fileserv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ pub async fn file_and_error_handler(
req: Request<Body>,
) -> AxumResponse {
let root = app_state.leptos_options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await.unwrap();
let res = get_static_file(
uri.clone(),
&root,
matches!(app_state.leptos_options.env, leptos_config::Env::PROD),
)
.await
.unwrap();

if res.status() == StatusCode::OK {
res.into_response()
Expand All @@ -39,6 +45,7 @@ pub async fn file_and_error_handler(
async fn get_static_file(
uri: Uri,
root: &str,
cache: bool,
) -> Result<Response<Body>, (StatusCode, String)> {
let req = Request::builder()
.uri(uri.clone())
Expand All @@ -47,7 +54,16 @@ async fn get_static_file(
// `ServeDir` implements `tower::Service` so we can call it with
// `tower::ServiceExt::oneshot` This path is relative to the cargo root
match ServeDir::new(root).oneshot(req).await {
Ok(res) => Ok(res.into_response()),
Ok(res) => {
let mut response = res.into_response();
if cache {
response.headers_mut().insert(
"Cache-Control",
"public, max-age=31536000, immutable".parse().unwrap(),
);
}
Ok(response)
}
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
Expand Down

0 comments on commit 5812a5b

Please sign in to comment.