我将 liberator 与 compojure 一起使用,并希望将多个方法(但不是所有方法)发送到保存资源。我不想重复自己,而是想要一次定义多个处理程序的东西。
一个例子:
(defroutes abc
(GET "/x" [] my-func)
(HEAD "/x" [] my-func)
(OPTIONS "/x" [] my-func))
应该更接近:
(defroutes abc
(GET-HEAD-OPTIONS "/x" [] my-func))
如教程中所示,惯用的方法是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)))
在几次错误的开始之后,我意识到 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)
似乎做我需要的。