-
Notifications
You must be signed in to change notification settings - Fork 13
/
follow_redirect.rb
36 lines (31 loc) · 996 Bytes
/
follow_redirect.rb
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
module RestCore
class FollowRedirect
def self.members; [:max_redirects]; end
include Middleware
def call env, &k
if env[DRY]
app.call(env, &k)
else
app.call(env){ |res| process(res, k) }
end
end
def process res, k
return k.call(res) if max_redirects(res) <= 0
status = res[RESPONSE_STATUS]
return k.call(res) if ![301,302,303,307].include?(status)
return k.call(res) if [301,302 ,307].include?(status) &&
![:get, :head ].include?(res[REQUEST_METHOD])
location = [res[RESPONSE_HEADERS]['LOCATION']].flatten.first
meth = if status == 303
:get
else
res[REQUEST_METHOD]
end
give_promise(call(res.merge(
REQUEST_METHOD => meth ,
REQUEST_PATH => location,
REQUEST_QUERY => {} ,
'max_redirects' => max_redirects(res) - 1), &k))
end
end
end