|
1 | 1 | (ns ring.core.protocols
|
2 | 2 | "Protocols necessary for Ring."
|
3 | 3 | {:added "1.6"}
|
4 |
| - (:import [java.io Writer OutputStream]) |
| 4 | + (:import [java.io OutputStream OutputStreamWriter Writer]) |
5 | 5 | (:require [clojure.java.io :as io]))
|
6 | 6 |
|
7 | 7 | (defprotocol ^{:added "1.6"} StreamableResponseBody
|
|
26 | 26 | (when-let [m (re-find re-charset content-type)]
|
27 | 27 | (or (m 1) (m 2))))
|
28 | 28 |
|
29 |
| -(defn- response-charset [response] |
| 29 | +(defn- response-charset ^String [response] |
30 | 30 | (some->> (:headers response)
|
31 | 31 | (some #(when (.equalsIgnoreCase "content-type" (key %)) (val %)))
|
32 | 32 | (find-charset-in-content-type)))
|
33 | 33 |
|
34 |
| -(defn- response-writer ^Writer [response output-stream] |
| 34 | +(defn- str->bytes [^String s ^String charset] |
| 35 | + (if charset (.getBytes s charset) (.getBytes s))) |
| 36 | + |
| 37 | +(defn- response-writer ^Writer [response ^OutputStream output-stream] |
35 | 38 | (if-let [charset (response-charset response)]
|
36 |
| - (io/writer output-stream :encoding charset) |
37 |
| - (io/writer output-stream))) |
| 39 | + (OutputStreamWriter. output-stream charset) |
| 40 | + (OutputStreamWriter. output-stream))) |
38 | 41 |
|
39 | 42 | ;; Extending primitive arrays prior to Clojure 1.12 requires using the low-level
|
40 | 43 | ;; extend function.
|
|
45 | 48 | (.write output-stream ^bytes body)
|
46 | 49 | (.close output-stream))})
|
47 | 50 |
|
| 51 | +;; Note: output streams are deliberately not closed on error, so that the |
| 52 | +;; adapter or error middleware can potentially send extra error information to |
| 53 | +;; the client. |
| 54 | + |
48 | 55 | (extend-protocol StreamableResponseBody
|
49 | 56 | String
|
50 | 57 | (write-body-to-stream [body response output-stream]
|
51 |
| - (doto (response-writer response output-stream) |
52 |
| - (.write body) |
53 |
| - (.close))) |
| 58 | + ;; No need to use a writer for a single string, and this prevents a |
| 59 | + ;; flush being used for a value of fixed length. |
| 60 | + (.write output-stream (str->bytes body (response-charset response))) |
| 61 | + (.close output-stream)) |
54 | 62 | clojure.lang.ISeq
|
55 | 63 | (write-body-to-stream [body response output-stream]
|
56 | 64 | (let [writer (response-writer response output-stream)]
|
|
0 commit comments