Skip to content

Commit 8fb7052

Browse files
committed
Add async support to wrap-default-charset
1 parent f9cceeb commit 8fb7052

2 files changed

Lines changed: 38 additions & 10 deletions

File tree

src/ring/middleware/default_charset.clj

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,24 @@
1010
(defn- contains-charset? [content-type]
1111
(re-find #";\s*charset=[^;]*" content-type))
1212

13-
(defn- add-charset [resp charset]
14-
(if-let [content-type (response/get-header resp "Content-Type")]
15-
(if (and (text-based-content-type? content-type)
16-
(not (contains-charset? content-type)))
17-
(response/charset resp charset)
18-
resp)
19-
resp))
13+
(defn default-charset-response
14+
"Add a default charset to a response if the response has no charset and
15+
requires one. See: wrap-default-charset."
16+
[response charset]
17+
(if response
18+
(if-let [content-type (response/get-header response "Content-Type")]
19+
(if (and (text-based-content-type? content-type)
20+
(not (contains-charset? content-type)))
21+
(response/charset response charset)
22+
response)
23+
response)))
2024

2125
(defn wrap-default-charset
2226
"Middleware that adds a charset to the content-type header of the response if
2327
one was not set by the handler."
2428
[handler charset]
25-
(fn [req]
26-
(if-let [resp (handler req)]
27-
(add-charset resp charset))))
29+
(fn
30+
([request]
31+
(default-charset-response (handler request) charset))
32+
([request respond raise]
33+
(handler request #(respond (default-charset-response % charset)) raise))))

test/ring/middleware/default_charset_test.clj

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,25 @@
3333
resp (handler request)]
3434
(is (= (:headers resp)
3535
{"Content-Type" "application/gzip"})))))
36+
37+
(deftest test-wrap-charset-cps
38+
(testing "content-type header without charset present"
39+
(let [handler (wrap-default-charset
40+
(fn [_ respond _] (respond (content-type {} "text/html")))
41+
"utf-16")
42+
resp (promise)
43+
ex (promise)]
44+
(handler request resp ex)
45+
(is (not (realized? ex)))
46+
(is (= (:headers @resp) {"Content-Type" "text/html; charset=utf-16"}))))
47+
48+
(testing "content-type header with charset present"
49+
(let [handler (wrap-default-charset
50+
(fn [_ respond _]
51+
(respond (-> {} (content-type "text/html") (charset "utf-8"))))
52+
"utf-16")
53+
resp (promise)
54+
ex (promise)]
55+
(handler request resp ex)
56+
(is (not (realized? ex)))
57+
(is (= (:headers @resp) {"Content-Type" "text/html; charset=utf-8"})))))

0 commit comments

Comments
 (0)