Question

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)))
Was it helpful?

Solution

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))})

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top