Skip to content

Instantly share code, notes, and snippets.

@techno-tanoC
Last active January 28, 2016 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techno-tanoC/7915d4ba5168c2198c2c to your computer and use it in GitHub Desktop.
Save techno-tanoC/7915d4ba5168c2198c2c to your computer and use it in GitHub Desktop.
pid = Progress.start_link "test.jpg"
HTTPoison.get! "url", %{}, stream_to: pid
defmodule Progress do
def start_link name do
{:ok, file} = File.open name, [:write]
spawn_link(fn -> loop(file, 0, 0) end)
end
def loop file, size, total do
receive do
%HTTPoison.AsyncChunk{chunk: chunk} ->
IO.inspect {size, total}
IO.binwrite file, chunk
chunk_size = byte_size chunk
loop file, (size + chunk_size), total
%HTTPoison.AsyncEnd{} ->
File.close file
%HTTPoison.Error{} ->
File.close file
%HTTPoison.AsyncHeaders{headers: headers} ->
loop file, size, content_length(headers)
%HTTPoison.AsyncRedirect{to: to} ->
reget to
loop file, size, total
_ ->
loop file, size, total
end
end
defp content_length headers do
Enum.find_value(headers,
fn {"Content-Length", total} -> String.to_integer total
_ -> false end)
end
defp reget! to do
HTTPoison.get! to, [], [stream_to: self, hackney: [follow_redirect: true]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment