Вопрос

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))
Это было полезно?

Решение 2

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.

Другие советы

As shown in the tutorial the idiomatic way is to use the ANY key on the route and then define the :allowed-methods [:get :head :options] on your resource. You will need to implement the :handle-ok and :handle-options

(defroute collection-example
    (ANY ["/collection/:id" #".*"] [id] (entry-resource id))
    (ANY "/collection" [] list-resource))


(defresource list-resource
  :available-media-types ["application/json"]
  :allowed-methods [:get :post]
  :known-content-type? #(check-content-type % ["application/json"])
  :malformed? #(parse-json % ::data)
  :handle-ok #(map (fn [id] (str (build-entry-url (get % :request) id)))
                   (keys @entries)))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top