Skip to content

Commit

Permalink
Add file response support to wrap-content-type
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
weavejester committed Oct 19, 2024
1 parent fef05a2 commit a66fe9e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
7 changes: 6 additions & 1 deletion ring-core/src/ring/middleware/content_type.clj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
(:require [ring.util.mime-type :refer [ext-mime-type]]
[ring.util.response :refer [content-type get-header]]))

(defn- guess-mime-type [{:keys [uri]} {:keys [body]} mime-types]
(or (ext-mime-type uri mime-types)
(when (instance? java.io.File body)
(ext-mime-type (str body) mime-types))))

(defn content-type-response
"Adds a content-type header to response. See: wrap-content-type."
{:added "1.2"}
Expand All @@ -12,7 +17,7 @@
(if response
(if (get-header response "Content-Type")
response
(let [mime-type (ext-mime-type (:uri request) (:mime-types options))]
(let [mime-type (guess-mime-type request response (:mime-types options))]
(content-type response (or mime-type "application/octet-stream")))))))

(defn wrap-content-type
Expand Down
10 changes: 9 additions & 1 deletion ring-core/test/ring/middleware/test/content_type.clj
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,15 @@
(let [response {:headers {"CoNteNt-typE" "application/x-overridden"}}
handler (wrap-content-type (constantly response))]
(is (= (handler {:uri "/foo/bar.png"})
{:headers {"CoNteNt-typE" "application/x-overridden"}})))))
{:headers {"CoNteNt-typE" "application/x-overridden"}}))))

(testing "fallback on response file extension"
(let [response {:body (java.io.File. "test/ring/assets/index.html")}
handler (wrap-content-type (constantly response))]
(is (= (-> (handler {:uri "/"}) (dissoc :body))
{:headers {"Content-Type" "text/html"}}))
(is (= (-> (handler {:uri "/index.txt"}) (dissoc :body))
{:headers {"Content-Type" "text/plain"}})))))

(deftest wrap-content-type-cps-test
(testing "response without content-type"
Expand Down

0 comments on commit a66fe9e

Please sign in to comment.