Skip to content
Browse files

Added ring.util.response/charset function (fixes #67)

  • Loading branch information...
1 parent cdee546 commit 0415c591af32e03bfe89f906916a7be7bbf057ce @weavejester weavejester committed
Showing with 22 additions and 0 deletions.
  1. +10 −0 ring-core/src/ring/util/response.clj
  2. +12 −0 ring-core/test/ring/util/test/response.clj
View
10 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."
View
12 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"))))

0 comments on commit 0415c59

Please sign in to comment.
Something went wrong with that request. Please try again.