Skip to content

Commit a66fe9e

Browse files
committed
Add file response support to wrap-content-type
If wrap-content-type cannot work out the content type from the URI, and it receives a response with a File as a body, it will attempt to work out what the content type is from the file extension of the response body.
1 parent fef05a2 commit a66fe9e

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

ring-core/src/ring/middleware/content_type.clj

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
(:require [ring.util.mime-type :refer [ext-mime-type]]
44
[ring.util.response :refer [content-type get-header]]))
55

6+
(defn- guess-mime-type [{:keys [uri]} {:keys [body]} mime-types]
7+
(or (ext-mime-type uri mime-types)
8+
(when (instance? java.io.File body)
9+
(ext-mime-type (str body) mime-types))))
10+
611
(defn content-type-response
712
"Adds a content-type header to response. See: wrap-content-type."
813
{:added "1.2"}
@@ -12,7 +17,7 @@
1217
(if response
1318
(if (get-header response "Content-Type")
1419
response
15-
(let [mime-type (ext-mime-type (:uri request) (:mime-types options))]
20+
(let [mime-type (guess-mime-type request response (:mime-types options))]
1621
(content-type response (or mime-type "application/octet-stream")))))))
1722

1823
(defn wrap-content-type

ring-core/test/ring/middleware/test/content_type.clj

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,15 @@
3939
(let [response {:headers {"CoNteNt-typE" "application/x-overridden"}}
4040
handler (wrap-content-type (constantly response))]
4141
(is (= (handler {:uri "/foo/bar.png"})
42-
{:headers {"CoNteNt-typE" "application/x-overridden"}})))))
42+
{:headers {"CoNteNt-typE" "application/x-overridden"}}))))
43+
44+
(testing "fallback on response file extension"
45+
(let [response {:body (java.io.File. "test/ring/assets/index.html")}
46+
handler (wrap-content-type (constantly response))]
47+
(is (= (-> (handler {:uri "/"}) (dissoc :body))
48+
{:headers {"Content-Type" "text/html"}}))
49+
(is (= (-> (handler {:uri "/index.txt"}) (dissoc :body))
50+
{:headers {"Content-Type" "text/plain"}})))))
4351

4452
(deftest wrap-content-type-cps-test
4553
(testing "response without content-type"

0 commit comments

Comments
 (0)