Skip to content
davidrupp edited this page Mar 23, 2012 · 3 revisions

Web applications often need to serve static content, such as images or stylesheets. Ring provides two middleware functions to do this.

One is wrap-file. This serves static content from a directory on the local filesystem:

(use 'ring.middleware.file)
(def app
  (wrap-file your-handler "/var/www/public"))

The other is wrap-resource. This serves static content from the JVM classpath:

(use 'ring.middleware.resource)
(def app
  (wrap-resource your-handler "public"))

If you're using a Clojure build tool like Leiningen or Cake, then the non-source-file resources for a project are kept in the "resources" directory. Files in this directory are automatically included in jar or war files.

So in the above example, files placed in the "resources/public" directory will in the public directory will be served up as static files.

Often you'll want to combine wrap-file or wrap-resource with the wrap-file-info middleware:

(use 'ring.middleware.resource
     'ring.middleware.file-info)

(def app
  (-> your-handler
      (wrap-resource "public")
      (wrap-file-info)))

The wrap-file-info middleware checks the modification dates and the file extension of the file, adding Content-Type and Last-Modified headers. This makes sure the browser knows the type of the file being served, and doesn't re-request the file if its already in the browser's cache.

Note that the wrap-file-info middleware needs to wrap around (i.e. come after) the wrap-resource or wrap-file functions.

Clone this wiki locally