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

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
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
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
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
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
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
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
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement