/
static.clj
63 lines (51 loc) · 1.94 KB
/
static.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
60
61
62
63
(ns duct.handler.static
(:require [clojure.java.io :as io]
[duct.core.resource :as resource]
[integrant.core :as ig]
[ring.util.mime-type :as mime]
[ring.util.response :as resp]))
(defn- merge-response [a b]
(-> a (assoc :body (:body b))
(update :headers (partial merge (:headers b)))))
(defn- guess-content-type [response name]
(if-let [mime-type (mime/ext-mime-type (str name))]
(resp/content-type response mime-type)
response))
(defprotocol ResponseBody
(update-response [body response]))
(extend-protocol ResponseBody
nil
(update-response [_ response] response)
Object
(update-response [_ response] response)
java.io.File
(update-response [f response]
(if-let [r (resp/file-response (str f))]
(-> response (merge-response r) (guess-content-type (str f)))
(assoc response :body nil)))
java.net.URL
(update-response [url response]
(if-let [r (resp/url-response url)]
(-> response (merge-response r) (guess-content-type (str url)))
(assoc response :body nil)))
duct.core.resource.Resource
(update-response [r response]
(update-response (io/as-url r) response)))
(defn- ring-response [response]
(update-response (:body response) response))
(defn- make-handler [response]
(fn
([_] (ring-response response))
([_ respond _] (respond (ring-response response)))))
(defmethod ig/init-key :duct.handler/static [_ response]
(make-handler response))
(defmethod ig/init-key ::ok [_ response]
(make-handler (assoc response :status 200)))
(defmethod ig/init-key ::bad-request [_ response]
(make-handler (assoc response :status 400)))
(defmethod ig/init-key ::not-found [_ response]
(make-handler (assoc response :status 404)))
(defmethod ig/init-key ::method-not-allowed [_ response]
(make-handler (assoc response :status 405)))
(defmethod ig/init-key ::internal-server-error [_ response]
(make-handler (assoc response :status 500)))