Permalink
Browse files

Added ring.middleware.json-response

  • Loading branch information...
1 parent cebe6c3 commit becd09841ec545e4f7307936a1224312e3310535 @weavejester committed Apr 7, 2012
Showing with 24 additions and 0 deletions.
  1. +15 −0 src/ring/middleware/json_response.clj
  2. +9 −0 test/ring/middleware/test/json_response.clj
@@ -0,0 +1,15 @@
+(ns ring.middleware.json-response
+ (:use ring.util.response)
+ (:require [cheshire.core :as json]))
+
+(defn wrap-json-response
+ "Middleware that converts responses with a map for a body into a JSON
+ response."
+ [handler]
+ (fn [request]
+ (let [response (handler request)]
+ (if (map? (:body response))
+ (-> response
+ (content-type "application/json")
+ (update-in [:body] json/generate-string))
+ response))))
@@ -0,0 +1,9 @@
+(ns ring.middleware.test.json-response
+ (:use ring.middleware.json-response
+ clojure.test))
+
+(deftest test-json-response
+ (let [handler (constantly {:status 200 :headers {} :body {:foo "bar"}})
+ response ((wrap-json-response handler) {})]
+ (is (= (get-in response [:headers "Content-Type"]) "application/json"))
+ (is (= (:body response) "{\"foo\":\"bar\"}"))))

0 comments on commit becd098

Please sign in to comment.