scoop

scoop

Req: Accumulating redirects - is this the proper way to go about it?

Dear all,

I threw together a custom step for req that accumulates the responses from the redirects that were followed.

Basically, I re-implemented the follow_redirects step from req and added accumulation which is then stored to the “private part” of the response.

Would you agree that this is the proper way to go about achieving this result?

The step

defmodule MyApp.FollowStoreRedirects do
  require Logger

  def attach(%Req.Request{} = request) do
    request
    |> Req.Request.prepend_response_steps(follow_redirects: &follow_store_redirects/1)
  end

  @doc step: :response
  defp follow_store_redirects(request_response)

  defp follow_store_redirects({request, response})
       when request.options.follow_redirects == false do
    {request, response}
  end

  defp follow_store_redirects({request, %{status: status} = response})
       when status in [301, 302, 303, 307, 308] do
    max_redirects = Map.get(request.options, :max_redirects, 10)
    redirect_count = Req.Request.get_private(request, :req_redirect_count, 0)
    stored_redirects = Req.Request.get_private(request, :stored_redirects, [])

    if redirect_count < max_redirects do
      request =
        request
        |> build_redirect_request(response)
        |> Req.Request.put_private(:req_redirect_count, redirect_count + 1)
        |> Req.Request.put_private(:stored_redirects, [response | stored_redirects])

      {_, result} = Req.Request.run(request)

      {Req.Request.halt(request), result}
    else
      raise "too many redirects (#{max_redirects})"
    end
  end

  defp follow_store_redirects({request, response}) do
    stored_redirects = Req.Request.get_private(request, :stored_redirects, [])

    {request,
     response
     |> Req.Response.put_private(:stored_redirects, stored_redirects)}
  end

  defp build_redirect_request(request, response) do
    {_, location} = List.keyfind(response.headers, "location", 0)
    Logger.debug(["follow_redirects: redirecting to : ", location])

    location_trusted = Map.get(request.options, :location_trusted)

    location_url = URI.merge(request.url, URI.parse(location))

    request
    |> remove_params()
    |> remove_credentials_if_untrusted(location_trusted, location_url)
    |> put_redirect_request_method()
    |> put_redirect_location(location_url)
  end

  defp put_redirect_request_method(request) when request.status in 307..308, do: request

  defp put_redirect_request_method(request), do: %{request | method: :get}

  defp remove_credentials_if_untrusted(request, true, _), do: request

  defp remove_credentials_if_untrusted(request, _, location_url) do
    if {location_url.host, location_url.scheme, location_url.port} ==
         {request.url.host, request.url.scheme, request.url.port} do
      request
    else
      remove_credentials(request)
    end
  end

  defp remove_credentials(request) do
    headers = List.keydelete(request.headers, "authorization", 0)
    request = update_in(request.options, &Map.delete(&1, :auth))
    %{request | headers: headers}
  end

  defp put_redirect_location(request, location_url) do
    put_in(request.url, location_url)
  end

  defp remove_params(request) do
    update_in(request.options, &Map.delete(&1, :params))
  end
end

Using the step

req =
  Req.new()
  |> MyApp.FollowStoreRedirects.attach()

Req.get!(req, url: "https://httpbin.org/redirect/5", max_redirects: 5)

Thank you in advance for any response and have a great rest of your day!

Marked As Solved

wojtekmach

wojtekmach

Hex Core Team

Instead of re-implementing follow_redirects I think you could prepend a custom step beforehand which upon getting 3xx response would save it off but then let follow_redirects do the actual redirect. Would that work?

Also Liked

scoop

scoop

Many thanks Wojtek!

*obviously that’s how to do it and I feel stupid right now

**was super pressed for time and wanted to explore it really quickly, not particularly wisely however

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New

We're in Beta

About us Mission Statement