witchcraft_server/service/
no_caching.rs1use crate::service::{Layer, Service};
15use http::header::{Entry, CACHE_CONTROL};
16use http::{HeaderValue, Method, Request, Response};
17
18#[allow(clippy::declare_interior_mutable_const)]
19const DO_NOT_CACHE: HeaderValue = HeaderValue::from_static("no-cache, no-store, must-revalidate");
20
21pub struct NoCachingLayer;
23
24impl<S> Layer<S> for NoCachingLayer {
25 type Service = NoCachingService<S>;
26
27 fn layer(self, inner: S) -> Self::Service {
28 NoCachingService { inner }
29 }
30}
31
32pub struct NoCachingService<S> {
33 inner: S,
34}
35
36impl<S, B1, B2> Service<Request<B1>> for NoCachingService<S>
37where
38 S: Service<Request<B1>, Response = Response<B2>> + Sync,
39 B1: Send,
40{
41 type Response = S::Response;
42
43 async fn call(&self, req: Request<B1>) -> Self::Response {
44 let is_get = req.method() == Method::GET;
45
46 let mut response = self.inner.call(req).await;
47 if is_get {
48 if let Entry::Vacant(e) = response.headers_mut().entry(CACHE_CONTROL) {
49 e.insert(DO_NOT_CACHE);
50 }
51 }
52
53 response
54 }
55}