Rocket icon indicating copy to clipboard operation
Rocket copied to clipboard

Draft: Allow specifying a cache-control header for serving static files.

Open dermesser opened this issue 2 years ago • 3 comments

Hi, first-time contributor here! I'd like to request some comments on this change before finalizing it and writing tests.

The idea is that when serving e.g. Javascript or image assets through Rocket, I'd like clients not to request the whole resource every time. I haven't found an established way of doing this in Rocket (except for serving static resources from a different webserver).

It's unclear to me if my solution is too hacky, but I've also not found a better place to implement this in. Maybe you can point me to it if there is.

dermesser avatar Jul 12 '22 20:07 dermesser

Not sure if this is useful here or not but, I currently use this to allow any type that implements a Responder trait to have a cache-control header:

use rocket::response;

pub struct CacheableResponse<T> {
    pub data: T,
    pub cache_control: String,
}

impl<'r, 'o: 'r, T: response::Responder<'r, 'o>> response::Responder<'r, 'o> for CacheableResponse<T> {
    fn respond_to(self, req: &'r rocket::Request<'_>) -> response::Result<'o> {
        response::Response::build_from(self.data.respond_to(req)?)
            .raw_header("Cache-Control", self.cache_control)
            .ok()
    }
}

Zusier avatar Jul 15 '22 02:07 Zusier

@Zusier thank you, this is my "backup plan", so to say :) I proposed adding this to the file serving code as it is likely a frequent need but I'm ok if your way is the "official" way going forward. (in that case I may file a PR for the documentation later :)

dermesser avatar Jul 15 '22 02:07 dermesser

I wanted to bundle my assets into a single binary, so I did something slightly different. Perhaps that's a bit too specific to be of any help help in this case though.

JockeTF avatar Jul 16 '22 20:07 JockeTF

Please see https://github.com/SergioBenitez/Rocket/issues/95#issuecomment-1492637801.

SergioBenitez avatar Apr 11 '23 17:04 SergioBenitez