Class: HttpMonkey::Middlewares::FollowRedirect
- Inherits:
-
Object
- Object
- HttpMonkey::Middlewares::FollowRedirect
- Defined in:
- lib/http_monkey/middlewares/follow_redirect.rb
Overview
Follow Redirects For response codes [301, 302, 303, 307], follow Location header. If header not found or tries is bigger than max_tries
, throw RuntimeError.
Example
HttpMonkey.configure do
middlewares.use HttpMonkey::M::FollowRedirect, :max_tries => 5 # default: 3
end
Constant Summary collapse
- InfiniteRedirectError =
Class.new(StandardError)
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ FollowRedirect
constructor
A new instance of FollowRedirect.
Constructor Details
#initialize(app, options = {}) ⇒ FollowRedirect
Returns a new instance of FollowRedirect.
17 18 19 20 21 |
# File 'lib/http_monkey/middlewares/follow_redirect.rb', line 17 def initialize(app, = {}) @app = app @max_tries = .fetch(:max_tries, 3) @follow_headers = .fetch(:headers, [301, 302, 303, 307]) end |
Instance Method Details
#call(env) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/http_monkey/middlewares/follow_redirect.rb', line 23 def call(env) current_try = 0 begin code, headers, body = @app.call(env) break unless @follow_headers.include?(code) location = (headers["Location"] || headers["location"]) raise RuntimeError, "HTTP status #{code}. No Location header." unless location env.uri = URI.parse(location) # change uri and submit again current_try += 1 raise RuntimeError, "Reached the maximum number of attempts in following url." if current_try > @max_tries end while true [code, headers, body] end |