-
Notifications
You must be signed in to change notification settings - Fork 12
/
response.clj
59 lines (49 loc) · 1.7 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
53
54
55
56
57
58
59
(ns ring.adapter.undertow.response
(:require
[ring.adapter.undertow.headers :refer [set-headers]]
[clojure.java.io :as io])
(:import
[clojure.lang ISeq]
[io.undertow.server HttpServerExchange]
[java.nio ByteBuffer]
[java.io File InputStream]))
(defprotocol RespondBody
(respond [_ ^HttpServerExchange exchange]))
(extend-protocol RespondBody
(Class/forName "[B")
(respond [^bytes body ^HttpServerExchange exchange]
(respond (ByteBuffer/wrap body) exchange))
String
(respond [body ^HttpServerExchange exchange]
(.send (.getResponseSender exchange) ^String body))
ByteBuffer
(respond [body ^HttpServerExchange exchange]
(.send (.getResponseSender exchange) ^ByteBuffer body))
InputStream
(respond [body ^HttpServerExchange exchange]
(if (.isInIoThread exchange)
(.dispatch exchange ^Runnable (^:once fn* [] (respond body exchange)))
(with-open [stream ^InputStream body]
(.startBlocking exchange)
(io/copy stream (.getOutputStream exchange))
(.endExchange exchange))))
File
(respond [f exchange]
(respond (io/input-stream f) exchange))
ISeq
(respond [body ^HttpServerExchange exchange]
(respond (reduce str body) exchange))
Object
(respond [body _]
(throw (UnsupportedOperationException. (str "Body class not supported: " (class body)))))
nil
(respond [_ ^HttpServerExchange exchange]
(.endExchange exchange)))
(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))