Sat*_*ish 2 clojure compojure ring
如何在Compojure/Ring中区分html vs xhr/xml/json请求,类似于Rails中的respond_to?
http://apidock.com/rails/ActionController/MimeResponds/respond_to
假设您确实希望基于Accept标头明确区分 - 而不是简单地根据Ankur的答案返回相应的响应类型,您可以创建自己的调度函数,如下所示.
(defn dispatch [m]
(let [req (ring-request)
accept (get (:headers req) "accept")
accept? #(re-find (re-pattern (str "^" %)) accept)
key (cond
(accept? "application/json") :json
(accept? "text/html") :html
:else :default)]
((key m))))
Run Code Online (Sandbox Code Playgroud)
然后像这样调用它
(defpage "/foo" []
(dispatch {:json (fn [] "{}")
:html (fn [] "html")
:default (fn [] "default")}))
Run Code Online (Sandbox Code Playgroud)
accept?上面的函数有点原始,但它可以作为一个起点.