-
Notifications
You must be signed in to change notification settings - Fork 12
/
response.clj
52 lines (44 loc) · 1.31 KB
/
response.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
(ns ring.adapter.undertow.response
(:require
[ring.adapter.undertow.headers :refer [set-headers]]
[clojure.java.io :as io])
(:import
[java.nio ByteBuffer]
[java.io File InputStream]
[io.undertow.io Sender]
[io.undertow.server HttpServerExchange]
[clojure.lang ISeq]))
(defn ^ByteBuffer str-to-bb
[^String s]
(ByteBuffer/wrap (.getBytes s "utf-8")))
(defprotocol RespondBody
(respond [_ ^HttpServerExchange exchange]))
(extend-protocol RespondBody
String
(respond [body ^HttpServerExchange exchange]
(.send ^Sender (.getResponseSender exchange) body))
InputStream
(respond [body ^HttpServerExchange exchange]
(with-open [^InputStream b body]
(io/copy b (.getOutputStream exchange))))
File
(respond [f exchange]
(respond (io/input-stream f) exchange))
ISeq
(respond [coll ^HttpServerExchange exchange]
(reduce
(fn [^Sender sender i]
(.send sender (str-to-bb i))
sender)
(.getResponseSender exchange)
coll))
nil
(respond [_ _]))
(defn set-exchange-response
[^HttpServerExchange exchange {:keys [status headers body]}]
(when-not exchange
(throw (Exception. "Null exchange given.")))
(when status
(.setStatusCode exchange status))
(set-headers (.getResponseHeaders exchange) headers)
(respond body exchange))