clojurecheshire

How can I make JSON responses be pretty-printed when using Rook?


I am using Rook framework for web services. I want to make API responses be pretty-printed. It seems that the response encoding is all handled by the wrap-restful-format function from ring.middleware.format. So I tried to replace the rook/wrap-with-standard-middleware function with my own version that passes different options through to ring.middleware.format.

(defn make-encoders-seq []
  [(ring.middleware.format-response/make-encoder
    (fn [s]
      (json/generate-string s {:pretty true}))
    "application/json")])

(defn wrap-with-standard-middleware-modified
  [handler]
  (-> handler
  (ring.middleware.format/wrap-restful-format :formats [:json-kw :edn]
                          :response-options
                          [:encoders (make-encoders-seq)])
  ring.middleware.keyword-params/wrap-keyword-params
  ring.middleware.params/wrap-params))

(def handler (-> (rook/namespace-handler
        ["resource" 'my-app.resource])
         (rook/wrap-with-injection :data-store venues)
         wrap-with-standard-middleware-modified))

This compiles fine but it doesn't work to pretty print the responses, it seems like the custom encoder is never called.


Solution

  • Try to change your format/wrap-restful-format to:

    (ring.middleware.format/wrap-restful-format :formats (concat (make-encoders-seq) [:edn])