Class: FaradayMiddleware::FollowRedirects

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/faraday_middleware/response/follow_redirects.rb

Overview

Public: Follow HTTP 301, 302, 303, and 307 redirects for GET, PATCH, POST, PUT, and DELETE requests.

This middleware does not follow the HTTP specification for HTTP 302, by default, in that it follows the improper implementation used by most major web browsers which forces the redirected request to become a GET request regardless of the original request method.

For HTTP 301, 302, and 303, the original request is transformed into a GET request to the response Location, by default. However, with standards compliance enabled, a 302 will instead act in accordance with the HTTP specification, which will replay the original request to the received Location, just as with a 307.

For HTTP 307, the original request is replayed to the response Location, including original HTTP request method (GET, POST, PUT, DELETE, PATCH), original headers, and original body.

This middleware currently only works with synchronous requests; in other words, it doesn’t support parallelism.

Constant Summary collapse

ALLOWED_METHODS =

HTTP methods for which 30x redirects can be followed

Set.new [:head, :options, :get, :post, :put, :patch, :delete]
REDIRECT_CODES =

HTTP redirect status codes that this middleware implements

Set.new [301, 302, 303, 307]
ENV_TO_CLEAR =

Keys in env hash which will get cleared between requests

Set.new [:status, :response, :response_headers]
FOLLOW_LIMIT =

Default value for max redirects followed

3
URI_UNSAFE =

Regex that matches characters that need to be escaped in URLs, sans the “%” character which we assume already represents an escaped sequence.

/[^\-_.!~*'()a-zA-Z\d;\/?:@&=+$,\[\]%]/

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ FollowRedirects

Public: Initialize the middleware.

options - An options Hash (default: {}):

 limit - A Numeric redirect limit (default: 3)
 standards_compliant - A Boolean indicating whether to respect
                       the HTTP spec when following 302
                       (default: false)
cookie - Use either an array of strings
        (e.g. ['cookie1', 'cookie2']) to choose kept cookies
        or :all to keep all cookies.


60
61
62
63
64
65
66
# File 'lib/faraday_middleware/response/follow_redirects.rb', line 60

def initialize(app, options = {})
  super(app)
  @options = options

  @replay_request_codes = Set.new [307]
  @replay_request_codes << 302 if standards_compliant?
end

Instance Method Details

#call(env) ⇒ Object



68
69
70
# File 'lib/faraday_middleware/response/follow_redirects.rb', line 68

def call(env)
  perform_with_redirection(env, follow_limit)
end