Skip to content

Commit 62b7264

Browse files
committed
add cache control middleware
1 parent 40ebe60 commit 62b7264

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

webserver/src/utils/mod.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,51 @@
1+
use std::future::Future;
2+
use std::pin::Pin;
3+
4+
use axum::handler::Handler;
5+
use axum::http::header::{CACHE_CONTROL, HeaderValue};
6+
use axum::http::request::Request;
7+
use axum::response::Response;
8+
19
pub mod sql {
210
use diesel::expression::functions::define_sql_function;
311
use diesel::sql_types::Integer;
412

513
define_sql_function!(fn abs(x: Integer) -> Integer);
614
}
15+
16+
pub const fn cache_forever<H>(handler: H) -> CacheControlMiddleware<H> {
17+
CacheControlMiddleware::new(handler)
18+
}
19+
20+
#[derive(Debug, Clone)]
21+
pub struct CacheControlMiddleware<H> {
22+
next_handler: H,
23+
}
24+
25+
impl<H> CacheControlMiddleware<H> {
26+
const CACHE_CONTROL_VALUE: &str = "public, max-age=31536000, immutable";
27+
28+
pub const fn new(next_handler: H) -> Self {
29+
Self { next_handler }
30+
}
31+
}
32+
33+
impl<T, S, B, H> Handler<T, S, B> for CacheControlMiddleware<H>
34+
where
35+
H: Handler<T, S, B>,
36+
S: Send + 'static,
37+
B: Send + 'static,
38+
{
39+
type Future = Pin<Box<dyn Future<Output = Response> + Send + 'static>>;
40+
41+
fn call(self, req: Request<B>, state: S) -> Self::Future {
42+
Box::pin(async move {
43+
let mut response = self.next_handler.call(req, state).await;
44+
response.headers_mut().insert(
45+
CACHE_CONTROL,
46+
HeaderValue::from_static(Self::CACHE_CONTROL_VALUE),
47+
);
48+
response
49+
})
50+
}
51+
}

0 commit comments

Comments
 (0)