Allow headers map/function for wrap-file? #42
If you just want a set of static headers, you can wrap your handler in another middleware function:
(defn wrap-headers [handler headers]
(fn [request]
(update-in (handler request) [:headers] merge headers)))
What's the advantage of adding this to the options map of an existing middleware function over just adding another layer of middleware?
Good point, but I do see a big advantage to allowing this option in the
wrap-file middleware. I would typically only want to set the aggressive
caching headers for static files. Which means the wrap-headers function
would have to know whether a given path points to a static file or the app.
Adding that functionality to wrap-headers would duplicate much of the logic
of wrap-files. It's the duplication that bothers me. As far as I can
figure, adding an option to wrap-files is the simplest way to avoid that
duplication.
You can tell whether a static file is being served by looking at the body:
(use '[ring.util.response :only header])
(defn wrap-cache-control [handler cache-control]
(fn [request]
(let [response (handler request)]
(if (instance? java.io.File (:body response))
(-> response (header "CacheControl" cache-control))
response))))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Setting headers, particularly cache-control, can be very important when serving static files. This is especially true in an environment like Heroku, where you're relying on a server-side HTTP cache to keep app requests down.
I propose a simple and flexible solution: supporting a new key in opts called
:headers. You can pass in a function or a map.If you pass in a map, then that becomes the headers map.
If you pass in a function, then the function will receive the path along with
opts. The developer-supplied function must return a map of headers. The purpose of allowing a function is to provide the greatest possible flexibility. (Developers may want to set headers differently depending on the path.)Sorry that I don't have time to write a patch now. I just wanted to pass this idea along. Thanks!