法拉第中间件知道什么时候被重定向

Faraday middleware know when something was redirected

我正在使用以下代码发出请求并遵循重定向:

require 'faraday'
require 'faraday_middleware'
conn = Faraday.new() do |f|
  f.use FaradayMiddleware::FollowRedirects, limit: 5
  f.adapter Faraday.default_adapter
end
resp = conn.get('http://www.example.com/redirect')
resp.status

此代码输出 200,因为它遵循了重定向,这很棒。但是有没有办法知道重定向是否存在?类似于 resp.redirected 如果遵循重定向则设置为 true 或如果未遵循重定向则设置为 false?

我在 FollowRedirects 代码中没有看到任何明显的内容。

如果我想知道这个,是否需要编写自己的自定义中间件?有谁知道可能已经做到这一点的中间件了吗?

实际上,我想我只是根据这里的 post 找到了答案:

我需要将我传入的原始 url 与生成的 url 进行比较。从上面扩展我的例子:

original_url = 'http://www.example.com/redirect'
resp = conn.get(original_url)
was_redirected = (original_url == resp.to_hash[:url].to_s)

我找到了解决办法。您可以将回调传递给 FaradayMiddleware::FollowRedirects。回调应该存在于 FollowRedirects 采用第二个参数的哈希中。由于我们必须为中间件使用 use 函数,因此您可以将哈希作为第二个参数传递给该函数。

  redirects_opts = {}

  # Callback function for FaradayMiddleware::FollowRedirects
  # will only be called if redirected to another url
  redirects_opts[:callback] = proc do |old_response, new_response|

    # you can pull the new redirected URL with this line of code.
    # since you have access to the new url you can make a variable or 
    # instance vairable to keep track of the current URL

    puts 'new url', new_response.url
  end

  @base_client = Faraday.new(url: url, ssl: { verify: true, verify_mode: 0 }) do |c|
    c.request :multipart
    c.request :url_encoded
    c.response :json, content_type: /\bjson$/
    c.use FaradayMiddleware::FollowRedirects, redirects_opts //<- pass hash here
    c.adapter Faraday.default_adapter
  end