From 0415c591af32e03bfe89f906916a7be7bbf057ce Mon Sep 17 00:00:00 2001 From: James Reeves Date: Fri, 6 Apr 2012 14:15:40 +0100 Subject: [PATCH] Added ring.util.response/charset function (fixes #67) --- ring-core/src/ring/util/response.clj | 10 ++++++++++ ring-core/test/ring/util/test/response.clj | 12 ++++++++++++ 2 files changed, 22 insertions(+) diff --git a/ring-core/src/ring/util/response.clj b/ring-core/src/ring/util/response.clj index 906a2f3..0f727a5 100644 --- a/ring-core/src/ring/util/response.clj +++ b/ring-core/src/ring/util/response.clj @@ -123,6 +123,16 @@ [resp content-type] (header resp "Content-Type" content-type)) +(defn charset + "Returns an updated Ring response with the supplied charset added to the + Content-Type header." + [resp charset] + (update-in resp [:headers "Content-Type"] + (fn [content-type] + (-> (or content-type "text/plain") + (str/replace #";\s*charset=[^;]*" "") + (str "; charset=" charset))))) + (defn set-cookie "Sets a cookie on the response. Requires the handler to be wrapped in the wrap-cookies middleware." diff --git a/ring-core/test/ring/util/test/response.clj b/ring-core/test/ring/util/test/response.clj index b7afeb9..8ebfdbf 100644 --- a/ring-core/test/ring/util/test/response.clj +++ b/ring-core/test/ring/util/test/response.clj @@ -28,6 +28,18 @@ (content-type {:status 200 :headers {"Content-Length" "10"}} "text/html")))) +(deftest test-charset + (testing "add charset" + (is (= (charset {:status 200 :headers {"Content-Type" "text/html"}} "UTF-8") + {:status 200 :headers {"Content-Type" "text/html; charset=UTF-8"}}))) + (testing "replace existing charset" + (is (= (charset {:status 200 :headers {"Content-Type" "text/html; charset=UTF-16"}} + "UTF-8") + {:status 200 :headers {"Content-Type" "text/html; charset=UTF-8"}}))) + (testing "default content-type" + (is (= (charset {:status 200 :headers {}} "UTF-8") + {:status 200 :headers {"Content-Type" "text/plain; charset=UTF-8"}})))) + (deftest test-header (is (= {:status 200 :headers {"X-Foo" "Bar"}} (header {:status 200 :headers {}} "X-Foo" "Bar"))))