clojurecompojureliberator

How do I handle some but not all http methods in compojure with Liberator?


I'm using liberator with compojure, and wanted to send multiple methods (but not all methods) to the save resource. Rather than repeating myself, I'd like to have something that defines multiple handlers at once.

An example:

(defroutes abc 
  (GET "/x" [] my-func)
  (HEAD "/x" [] my-func)
  (OPTIONS "/x" [] my-func))

Should be closer to:

(defroutes abc
  (GET-HEAD-OPTIONS "/x" [] my-func))

Solution

  • After several false starts, I realized that the compojure.core/context macro can be used for this purpose. I defined the following macro:

    (defmacro read-only "Generate a route that matches HEAD, GET, or OPTIONS"
      [path args & body]
      `(context "" []
            (GET ~path ~args ~@body)
            (HEAD ~path ~args ~@body)
            (OPTIONS ~path ~args ~@body)))
    

    Which will let you do:

    (read-only "/x" [] my-func)
    

    And seems to do what I need.