Skip to content

Commit 79d1b73

Browse files
authored
Merge pull request #60 from namada-net/tiago/add-cache-control-headers
add cache control headers
2 parents 4ebee05 + 3c1d83d commit 79d1b73

File tree

2 files changed

+50
-4
lines changed

2 files changed

+50
-4
lines changed

webserver/src/app.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use crate::appstate::AppState;
2020
use crate::config::AppConfig;
2121
use crate::handler;
2222
use crate::state::common::CommonState;
23+
use crate::utils::cache_forever;
2324

2425
lazy_static! {
2526
static ref HTTP_TIMEOUT: u64 = 60;
@@ -43,17 +44,17 @@ impl ApplicationServer {
4344
Router::new()
4445
.route(
4546
"/commitment-tree",
46-
get(handler::tree::get_commitment_tree),
47+
get(cache_forever(handler::tree::get_commitment_tree)),
4748
)
4849
.route(
4950
"/witness-map",
50-
get(handler::witness_map::get_witness_map),
51+
get(cache_forever(handler::witness_map::get_witness_map)),
5152
)
5253
.route(
5354
"/notes-index",
54-
get(handler::notes_index::get_notes_index),
55+
get(cache_forever(handler::notes_index::get_notes_index)),
5556
)
56-
.route("/tx", get(handler::tx::get_tx))
57+
.route("/tx", get(cache_forever(handler::tx::get_tx)))
5758
.route("/height", get(handler::namada_state::get_latest_height))
5859
.route(
5960
"/block-index",

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::body::Body;
5+
use axum::handler::Handler;
6+
use axum::http::header::{CACHE_CONTROL, HeaderValue};
7+
use axum::http::request::Request;
8+
use axum::response::Response;
9+
110
pub mod sql {
211
use diesel::expression::functions::define_sql_function;
312
use diesel::sql_types::Integer;
413

514
define_sql_function!(fn abs(x: Integer) -> Integer);
615
}
16+
17+
pub const fn cache_forever<H>(handler: H) -> CacheControlMiddleware<H> {
18+
CacheControlMiddleware::new(handler)
19+
}
20+
21+
#[derive(Debug, Clone)]
22+
pub struct CacheControlMiddleware<H> {
23+
next_handler: H,
24+
}
25+
26+
impl<H> CacheControlMiddleware<H> {
27+
const CACHE_CONTROL_VALUE: &str = "public, max-age=31536000, immutable";
28+
29+
pub const fn new(next_handler: H) -> Self {
30+
Self { next_handler }
31+
}
32+
}
33+
34+
impl<T, S, H> Handler<T, S> for CacheControlMiddleware<H>
35+
where
36+
H: Handler<T, S>,
37+
S: Send + 'static,
38+
{
39+
type Future = Pin<Box<dyn Future<Output = Response> + Send + 'static>>;
40+
41+
fn call(self, req: Request<Body>, 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)