Set cache control headers for the static files.

This commit is contained in:
Tom Alexander 2023-08-18 15:50:22 -04:00
parent bff0a62291
commit 893de9a65e
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
3 changed files with 18 additions and 10 deletions

1
Cargo.lock generated
View File

@ -394,6 +394,7 @@ dependencies = [
"nom",
"serde",
"tokio",
"tower",
"tower-http",
]

View File

@ -8,4 +8,5 @@ axum = { git = "https://github.com/tokio-rs/axum.git", rev = "52a90390195e884bcc
nom = "7.1.1"
serde = { version = "1.0.183", features = ["derive"] }
tokio = { version = "1.30.0", default-features = false, features = ["macros", "process", "rt", "rt-multi-thread"] }
tower-http = { version = "0.4.3", features = ["fs"] }
tower = "0.4.13"
tower-http = { version = "0.4.3", features = ["fs", "set-header"] }

View File

@ -1,11 +1,13 @@
#![feature(exit_status_error)]
use axum::http::header::CACHE_CONTROL;
use axum::http::HeaderMap;
use axum::http::HeaderValue;
use axum::response::IntoResponse;
use axum::{http::StatusCode, routing::post, Json, Router};
use owner_tree::build_owner_tree;
use parse::emacs_parse_org_document;
use tower::ServiceBuilder;
use tower_http::services::{ServeDir, ServeFile};
use tower_http::set_header::SetResponseHeaderLayer;
mod error;
mod owner_tree;
@ -14,10 +16,20 @@ mod sexp;
#[tokio::main]
async fn main() {
let serve_dir = ServeDir::new("static").not_found_service(ServeFile::new("static/index.html"));
let static_files_service = {
let serve_dir =
ServeDir::new("static").not_found_service(ServeFile::new("static/index.html"));
ServiceBuilder::new()
.layer(SetResponseHeaderLayer::if_not_present(
CACHE_CONTROL,
HeaderValue::from_static("public, max-age=120"),
))
.service(serve_dir)
};
let app = Router::new()
.route("/parse", post(parse_org_mode))
.fallback_service(serve_dir);
.fallback_service(static_files_service);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
@ -34,9 +46,3 @@ async fn _parse_org_mode(body: String) -> Result<impl IntoResponse, Box<dyn std:
let owner_tree = build_owner_tree(body.as_str(), ast.as_str()).map_err(|e| e.to_string())?;
Ok((StatusCode::OK, Json(owner_tree)))
}
fn no_cache_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(CACHE_CONTROL, "public, max-age=120".parse().unwrap());
headers
}