我正在使用带有compojure的liberator,并希望向save资源发送多个方法(但不是所有方法)。我不想重复自己,而是希望能够同时定义多个处理程序。
一个例子:
(defroutes abc
(GET "/x" [] my-func)
(HEAD "/x" [] my-func)
(OPTIONS "/x" [] my-func))
应该更接近:
(defroutes abc
(GET-HEAD-OPTIONS "/x" [] my-func))
答案 0 :(得分:2)
如tutorial所示,惯用方法是在路线上使用ANY
键,然后在资源上定义:allowed-methods [:get :head :options]
。您需要实施:handle-ok
和: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)))
答案 1 :(得分:1)
经过几次错误的启动后,我意识到compojure.core / context宏可以用于此目的。我定义了以下宏:
(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)))
您可以这样做:
(read-only "/x" [] my-func)
似乎做了我需要的事。