我如何处理一些但不是所有与解放者组合的HTTP方法



我正在将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)))

几次false启动后,我意识到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)

似乎可以做我需要的事情。

最新更新