How to set the status code in Compojure?

拜拜、爱过 提交于 2019-12-23 21:53:18

问题


I am writing a small website in Clojure and Compojure. I would like to set the HTTP response status for each request based on the data found or not found.

The last call is the html5 macro that returns to the handler the html that needs to be sent back to the browser. Is it possible to set the HTTP response status somehow here?

(ns myapp.views.layout
  (:require
    [hiccup.page :refer (html5 include-css include-js)]))

(defn layout [title & content]
  (html5
    (head title)
    (body content)))

回答1:


If you only return text that text will be the body of the response. If you return a map, the map can describe other aspects of the response.

(defn layout [title & content]
  {:status 200
   :body (html5 (head title) (body content))})



回答2:


If you return a map containing

{:status NNN
 :body (my-code-here)}

then the contents of the :status key will be the http response code.




回答3:


Just to add some details that might be helpful or interesting to others, each of the return values of your Compojure route handlers "... is treated intelligently" and that intelligence is encapsulated in the "compojure.response/render multimethod".

Based on a cursory examination of the render code, the reason why returning a map works is that the map you return is merge-d with the Ring response map that Compojure implicitly creates.

You might also want to include :headers {"Content-Type" "text/html"} (or whatever's appropriate) in the map for your handler return values. A Unicode character in the page title in my responses wasn't being rendered correctly because the content type header was missing.



来源:https://stackoverflow.com/questions/22798004/how-to-set-the-status-code-in-compojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!