How to download a file with Finch which is redirected

Hi, I want to download a file from GitHub, but Finch returns 302 status and can’t download.

for example:

 %Finch.Response{
   status: 302,
   body: "",
   headers: [
     {"server", "GitHub.com"},
     {"date", "Mon, 19 Sep 2022 11:41:40 GMT"},
     {"content-type", "text/html;charset=utf-8"},
     {"content-length", "0"},
     {"cache-control", "public, must-revalidate, max-age=0"},
     {"expires", "Mon, 19 Sep 2022 11:41:40 GMT"},
     {"location",
      "https://codeload.github.com/mishka-group/mishka-cms/legacy.tar.gz/refs/tags/0.0.2"},

In location section you can see the real link after redirection, if I use this it works, but I need to know how to force Finch download automatically links maybe are redirected.


Block code:

Finch.build(:get, "https://api.github.com/repos/mishka-group/mishka-cms/tarball/0.0.2")
|> Finch.request(@request_name)

Thank you in advance

1 Like

There’s no built-in feature inside Finch which follow redirects. You can write your own wrapper for this. For example

def do_get(url, name, depth \\ 123)
def do_get(:undefined, _, _), do: {:error, :bad_redirect}
def do_get(url, name, 0), do: {:error, :maximum_depth_exceeded}
def do_get(url, name, depth) do
  :get
  |> Finch.build(url)
  |> Finch.request(name)
  |> case do
    {:ok, %Finch.Response{status: 302, headers: headers}} ->
      "location"
      |> :proplists.get_value(headers)
      |> do_get(name, depth - 1)

    other ->
      other
  end
end
2 Likes

Thank you, yes I know we can get from location, but I thought there is an option for this problem.

Apologies that I am not answering your question directly but I would strongly recommend you use Tesla with Finch below. Tesla has a number of these super useful wrappers, redirect following being one of them.

1 Like

Thank you for suggestion, sure I will test it :rose:

As I’ve said, there’s no such option. I’ve read the sources and it doesn’t support redirects out of the box

1 Like