Allow headers map/function for wrap-file? #42

Closed
jarrett opened this Issue Nov 17, 2011 · 4 comments

2 participants

@jarrett

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!

@weavejester
Collaborator

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?

@jarrett
@weavejester
Collaborator

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))))
@jarrett
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment