Last active
January 28, 2016 09:31
-
-
Save techno-tanoC/7915d4ba5168c2198c2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pid = Progress.start_link "test.jpg" | |
HTTPoison.get! "url", %{}, stream_to: pid |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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