//! Additional HTTP headers for browser cache management.
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::Header;
use rocket::{Request, Response};
/// The `Cache-Control` HTTP header field holds directives (instructions) — in both requests and responses — that control caching in browsers and shared caches (e.g. Proxies, CDNs).
///
/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control>
pub struct CacheControl;
#[rocket::async_trait]
impl Fairing for CacheControl {
fn info(&self) -> Info {
Info {
name: "Add Cache-Control header to responses",
kind: Kind::Response,
}
}
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
// 2592000 = 30 * 24 * 60 * 60
response.set_header(Header::new(
"Cache-Control",
"public, max-age=2592000, immutable",
));
}
}
/// Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
///
/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>
pub struct Cors;
#[rocket::async_trait]
impl Fairing for Cors {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to responses",
kind: Kind::Response,
}
}
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
response.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, OPTIONS",
));
response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
}