luminus-framework/luminus

Hiccup format from http handlers

elmehalawi opened this issue · 2 comments

I'm trying to get a feel for luminus and clj dev in general. I did lein new luminus whatever to make a new project, and I tried replacing the home-page handler with a new one:

(defn home-page [request]
  (html "hello"))

And I get the following error:

ERROR ziftbook.middleware - contains? not supported on type: java.lang.String
java.lang.IllegalArgumentException: contains? not supported on type: java.lang.String

I guess this is because the handlers are actually expected to return requests, so I tried this instead:

(defn home-page [request]
  {:status 200
   :body (html "hello")
   :headers {:content-type "text/html"}})

Now I get the following error:

ERROR ziftbook.middleware - class clojure.lang.Keyword cannot be cast to class java.lang.String (clojure.lang.Keyword is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')

The docs say you can use hiccup, but I'm not totally sure how.

Also I know you shouldn't put the hiccup in the actual handlers, but this is a minimal example.

the problem there is with :content-type in headers, if you change it to:

{:status 200
 :body (html "hello")
 :headers {"Content-Type" "text/html"}}

that should work as expected. However, a better way to do it would be:

(ns myapp.routes.home
  (:require
   [hiccup.core :refer [html]]
   [myapp.middleware :as middleware]
   [ring.util.response]
   [ring.util.http-response :as response]))

(defn home-page [request]
  (-> (html [:html [:body [:span {:class "foo"} "Hello"]]])
      (response/ok)
      (response/content-type "text/html; charset=utf-8")))

(defn home-routes []
  [ "" 
   {:middleware [middleware/wrap-csrf
                 middleware/wrap-formats]}
   ["/" {:get home-page}]])

Thank you very much, that is definitely better.