2

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.

  • Rook 1.3.9
  • ring-middleware-format 0.6.0
  • cheshire 5.4.0 (for json/generate-string in above)
M--
  • 25,431
  • 8
  • 61
  • 93
amoe
  • 4,473
  • 4
  • 31
  • 51

1 Answers1

2

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

(ring.middleware.format/wrap-restful-format :formats (concat (make-encoders-seq) [:edn])
DanLebrero
  • 8,545
  • 1
  • 29
  • 30
  • Perfect. Any idea why this works? I wasn't able to see where it is documented that the value for `:formats` can contain encoders as well as keywords. – amoe Jan 27 '16 at 15:28
  • 2
    I just read the source code of ring-mw-format https://github.com/ngrunwald/ring-middleware-format/blob/release-0.6.0/src/ring/middleware/format_response.clj#L374. See how if the `format` is a map, it will just use it as it is. – DanLebrero Jan 27 '16 at 15:53