Permalink
Browse files

Improved content-type parsing; added character encoding unit tests

  • Loading branch information...
1 parent 0ef8aaf commit bd8a0b37435ca682588a78752c3774f735df2800 @weavejester weavejester committed Jul 6, 2011
Showing with 27 additions and 5 deletions.
  1. +17 −4 ring-servlet/src/ring/util/servlet.clj
  2. +10 −1 ring-servlet/test/ring/util/servlet_test.clj
View
21 ring-servlet/src/ring/util/servlet.clj
@@ -60,6 +60,21 @@
[^HttpServletResponse response, status]
(.setStatus response status))
+(defn set-content-type [response content-type]
+ (.setContentType
+ response
+ (-> content-type
+ (string/split #";")
+ first
+ string/trim)))
+
+(defn- set-character-encoding [response content-type]
+ (.setCharacterEncoding
+ response
+ (-> (re-find #"charset=(.+);?" content-type)
+ second
+ (or "utf-8"))))
+
(defn set-headers
"Update a HttpServletResponse with a map of headers."
[^HttpServletResponse response, headers]
@@ -70,10 +85,8 @@
(.addHeader response key val))))
; Some headers must be set through specific methods
(when-let [content-type (get headers "Content-Type")]
- ; Parse charset and set response encoding from it or set UTF-8 by default
- (let [encoding (or (second (re-find #"charset=(.+);?" content-type)) "utf-8")]
- (.setCharacterEncoding response encoding))
- (.setContentType response content-type)))
+ (set-character-encoding response content-type)
+ (set-content-type response content-type)))
(defn- set-body
"Update a HttpServletResponse body with a String, ISeq, File or InputStream."
View
11 ring-servlet/test/ring/util/servlet_test.clj
@@ -88,4 +88,13 @@
(run-servlet handler request response)
(is (= (@response :status) 200))
(is (= (@response :content-type) "text/plain"))
- (is (= (get-in @response [:headers "X-Server"]) "Bar"))))))
+ (is (= (@response :character-encoding) "utf-8"))
+ (is (= (get-in @response [:headers "X-Server"]) "Bar"))))
+ (testing "response with character encoding"
+ (letfn [(handler [r]
+ {:status 200
+ :headers {"Content-Type" "text/plain; charset=utf-16"}
+ :body nil})]
+ (run-servlet handler request response)
+ (is (= (@response :content-type) "text/plain"))
+ (is (= (@response :character-encoding) "utf-16"))))))

0 comments on commit bd8a0b3

Please sign in to comment.