Using compojure.route/resources and ring.middleware.resource/wrap-resource

clojure, compojure, ring

Solution

Main difference is `compojure.route/resources` only serve resources from a specific path:

 (let [root (:root options "public")]
      (resource-response (str root "/" resource-path))

But `ring.middleware.resource/wrap-resource` provides a fail-back mechanism on a handler if no resource is found:

 (or (response/resource-response path {:root root-path})
     (handler request))

As you see from the `resource-response` function both alternatives use:

 (defn resource-response
  "Returns a Ring response to serve a packaged resource, or nil if the
   resource does not exist.
  Options:
    :root - take the resource relative to this root"

It returns `nil` if the requested resource is not found.

So the `wrap-resource` alternative is more suitable to be chained if you already have routes in place, as in:

(defroutes routes
  (GET "/" [] "<h1>Hello World</h1>")
  (route/not-found "<h1>Page not found</h1>"))

(def app (-> routes 
             (wrap-resource "public/resources"))

And the `compojure.route/resources` you can use for route composition, as in:

 (defroutes resources-routes
    (route/resources "/"))

 (defroutes routes
   (GET "/" [] "<h1>Hello World</h1>")
   (route/not-found "<h1>Page not found</h1>"))

 (def app
   (compojure.core/routes
       resources-routes
       routes))

Problem

I am trying to learn clojure web development with ring and compojure and I am a little unclear about the usage of `compojure.route/resources` and `ring.middleware.resource/wrap-resource`. I have looked over the API docs, as well as the source for both `compojure.route` and `ring.middleware.resource`. However, I am still unclear as to whether one needs to use both the `compojure.route/resources` route and the `ring.middleware.resource/wrap-resource` middleware, or if `compojure.route/resources` takes care of everything. Or is it a matter of optimization? As in, using `wrap-resource` avoids the compojure routing overhead? Any insights would be greatly appreciated.

Original source