Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faraday middleware know when something was redirected

Tags:

ruby

faraday

I'm using the following code to make a request and follow redirects:

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

This code outputs 200 because it followed the redirect, which is great. But is there anyway to know if a redirect existed or not? something like resp.redirected which is set to true if a redirect was followed or false if no redirect was followed?

I didn't see anything obvious in the FollowRedirects code.

Will I need to write my own custom middleware if I want to know this? Does anyone know of middleware out there that might do this already?

like image 860
Russ Savage Avatar asked Oct 24 '25 21:10

Russ Savage


1 Answers

I found a solution. You can pass a callback to FaradayMiddleware::FollowRedirects. The callback should live in a hash that the FollowRedirects takes a second parameter. Since we have to use the use function for middleware you can pass the hash as a second parameter to that function.

  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
like image 178
Marcellino Ornelas Avatar answered Oct 27 '25 11:10

Marcellino Ornelas