Permalink
Browse files

Added content-type middleware

  • Loading branch information...
1 parent b0f754f commit 2f2179d4662f8586d797cf96c4310ad70a04b8ee @weavejester weavejester committed Feb 27, 2011
View
22 ring-core/src/ring/middleware/content_type.clj
@@ -0,0 +1,22 @@
+(ns ring.middleware.content-type
+ "Middleware for automatically adding a content type to response maps."
+ (:use ring.util.mime-type
+ ring.util.response))
+
+(defn wrap-content-type
+ "Middleware that adds a content-type header to the response if one is not
+ set by the handler. Uses the ring.util.mime-type/ext-mime-type function to
+ guess the content-type from the file extension in the URI. If no
+ content-type can be found, it defaults to 'application/octet-stream'.
+
+ Accepts the following options:
+ :mime-types - a map of filename extensions to mime-types that will be
+ used in addition to the ones defined in
+ ring.util.mime-types/default-mime-types"
+ [handler & [opts]]
+ (fn [req]
+ (let [resp (handler req)]
+ (if (get-in resp [:headers "Content-Type"])
+ resp
+ (let [mime-type (ext-mime-type (:uri req) (:mime-types opts))]
+ (content-type resp (or mime-type "application/octet-stream")))))))
View
26 ring-core/test/ring/middleware/content_type_test.clj
@@ -0,0 +1,26 @@
+(ns ring.middleware.content-type-test
+ (:use clojure.test
+ ring.middleware.content-type))
+
+(deftest wrap-content-type-test
+ (testing "response without content-type"
+ (let [response {:headers {}}
+ handler (wrap-content-type (constantly response))]
+ (is (= (handler {:uri "/foo/bar.png"})
+ {:headers {"Content-Type" "image/png"}}))
+ (is (= (handler {:uri "/foo/bar.txt"})
+ {:headers {"Content-Type" "text/plain"}}))))
+
+ (testing "response with content-type"
+ (let [response {:headers {"Content-Type" "application/x-foo"}}
+ handler (wrap-content-type (constantly response))]
+ (is (= (handler {:uri "/foo/bar.png"})
+ {:headers {"Content-Type" "application/x-foo"}}))))
+
+ (testing "unknown file extension"
+ (let [response {:headers {}}
+ handler (wrap-content-type (constantly response))]
+ (is (= (handler {:uri "/foo/bar.xxxaaa"})
+ {:headers {"Content-Type" "application/octet-stream"}}))
+ (is (= (handler {:uri "/foo/bar"})
+ {:headers {"Content-Type" "application/octet-stream"}})))))

0 comments on commit 2f2179d

Please sign in to comment.