Skip to content

Commit 3b5bcf8

Browse files
committed
add missing cache-header middleware to axum app
1 parent dfe5d64 commit 3b5bcf8

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/web/cache.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
use super::STATIC_FILE_CACHE_DURATION;
22
use crate::config::Config;
3+
use axum::{
4+
http::Request as AxumHttpRequest, middleware::Next, response::Response as AxumResponse,
5+
};
6+
use http::header::CACHE_CONTROL;
37
use iron::{
48
headers::{CacheControl, CacheDirective},
59
AfterMiddleware, IronResult, Request, Response,
610
};
11+
use std::sync::Arc;
712

813
#[cfg(test)]
914
pub const NO_CACHE: &str = "max-age=0";
@@ -112,6 +117,40 @@ impl AfterMiddleware for CacheMiddleware {
112117
}
113118
}
114119

120+
pub(crate) async fn cache_middleware<B>(req: AxumHttpRequest<B>, next: Next<B>) -> AxumResponse {
121+
let config = req
122+
.extensions()
123+
.get::<Arc<Config>>()
124+
.cloned()
125+
.expect("missing config extension in request");
126+
127+
let mut response = next.run(req).await;
128+
129+
let cache = response
130+
.extensions()
131+
.get::<CachePolicy>()
132+
.unwrap_or(&CachePolicy::NoCaching);
133+
134+
if cfg!(test) {
135+
assert!(
136+
!response.headers().contains_key(CACHE_CONTROL),
137+
"handlers should never set their own caching headers and only use CachePolicy to control caching."
138+
);
139+
}
140+
141+
let directives = cache.render(&config);
142+
if !directives.is_empty() {
143+
response.headers_mut().insert(
144+
CACHE_CONTROL,
145+
CacheControl(directives)
146+
.to_string()
147+
.parse()
148+
.expect("cache-control header could not be parsed"),
149+
);
150+
}
151+
response
152+
}
153+
115154
#[cfg(test)]
116155
mod tests {
117156
use super::*;

src/web/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,8 @@ pub(crate) fn build_axum_app(
447447
.layer(middleware::from_fn(csp::csp_middleware))
448448
.layer(middleware::from_fn(
449449
page::web_page::render_templates_middleware,
450-
)),
450+
))
451+
.layer(middleware::from_fn(cache::cache_middleware)),
451452
))
452453
}
453454

0 commit comments

Comments
 (0)