问题
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