Skip to content

Commit f9cceeb

Browse files
committed
Add async support to wrap-absolute-redirects
1 parent 05b78b5 commit f9cceeb

2 files changed

Lines changed: 43 additions & 5 deletions

File tree

src/ring/middleware/absolute_redirects.clj

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,22 @@
2828
(let [url (URL. (req/request-url request))]
2929
(str (URL. url location)))))
3030

31+
(defn absolute-redirects-response
32+
"Convert a response that redirects to a relative URLs into a response that
33+
redirects to an absolute URL. See: wrap-absolute-redirects."
34+
[response request]
35+
(if (redirect? response)
36+
(update-header response "location" absolute-url request)
37+
response))
38+
3139
(defn wrap-absolute-redirects
3240
"Middleware that converts redirects to relative URLs into redirects to
3341
absolute URLs. While many browsers can handle relative URLs in the Location
3442
header, RFC 2616 states that the Location header must contain an absolute
3543
URL."
3644
[handler]
37-
(fn [request]
38-
(let [response (handler request)]
39-
(if (redirect? response)
40-
(update-header response "location" absolute-url request)
41-
response))))
45+
(fn
46+
([request]
47+
(absolute-redirects-response (handler request) request))
48+
([request respond raise]
49+
(handler request #(respond (absolute-redirects-response % request)) raise))))

test/ring/middleware/absolute_redirects_test.clj

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,33 @@
4343
resp (handler (request :post "/bar"))]
4444
(is (= (:status resp) 201))
4545
(is (= (:headers resp) {"Location" "http://localhost/bar/1"})))))
46+
47+
(deftest test-wrap-absolute-redirects-cps
48+
(testing "relative redirects"
49+
(let [handler (wrap-absolute-redirects (fn [_ respond _] (respond (redirect "/foo"))))
50+
resp (promise)
51+
ex (promise)]
52+
(handler (request :get "/") resp ex)
53+
(is (not (realized? ex)))
54+
(is (= (:status @resp) 302))
55+
(is (= (:headers @resp) {"Location" "http://localhost/foo"}))))
56+
57+
(testing "absolute redirects"
58+
(let [handler (wrap-absolute-redirects
59+
(fn [_ respond _] (respond (redirect "http://example.com"))))
60+
resp (promise)
61+
ex (promise)]
62+
(handler (request :get "/") resp ex)
63+
(is (not (realized? ex)))
64+
(is (= (:status @resp) 302))
65+
(is (= (:headers @resp) {"Location" "http://example.com"}))))
66+
67+
(testing "no redirects"
68+
(let [handler (wrap-absolute-redirects (fn [_ respond _] (respond (response "hello"))))
69+
resp (promise)
70+
ex (promise)]
71+
(handler (request :get "/bar/baz.html") resp ex)
72+
(is (not (realized? ex)))
73+
(is (= (:status @resp) 200))
74+
(is (= (:headers @resp) {}))
75+
(is (= (:body @resp) "hello")))))

0 commit comments

Comments
 (0)