use std::fmt::Write;
use axum::http::{HeaderMap, HeaderValue};
pub struct CacheContext {
pub is_get: bool,
pub has_auth: bool,
pub query_ttl: Option<u64>,
pub default_ttl: u64,
pub cdn_max_age: Option<u64>,
}
pub fn apply_cache_headers(headers: &mut HeaderMap, ctx: &CacheContext) {
if ctx.is_get {
let max_age = ctx.query_ttl.unwrap_or(ctx.default_ttl);
let visibility = if ctx.has_auth { "private" } else { "public" };
let mut value = format!("{visibility}, max-age={max_age}");
if !ctx.has_auth {
if let Some(s_maxage) = ctx.cdn_max_age {
write!(value, ", s-maxage={s_maxage}").expect("write to String");
}
}
if let Ok(val) = HeaderValue::from_str(&value) {
headers.insert("cache-control", val);
}
headers.insert("vary", HeaderValue::from_static("Authorization, Accept, Prefer"));
} else {
headers.insert("cache-control", HeaderValue::from_static("no-store"));
}
}