-
-
Save amokan/36ff8017146fdf27d5fcb32c451655b7 to your computer and use it in GitHub Desktop.
Streaming Size Check
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 StreamTest do | |
use GenServer | |
require Logger | |
def start_link(opts \\ []) do | |
GenServer.start_link(__MODULE__, :ok, opts) | |
end | |
def init(:ok) do | |
Process.flag :trap_exit, true | |
send(self(), :start_request) | |
{:ok, %{file: "", poison: nil}} | |
end | |
def terminate(:normal, state), do: {:noreply, state} | |
def terminate(reason, state) do | |
Logger.warn("Terminate in #{inspect __MODULE__}. Reason: #{inspect reason}") | |
{:noreply, state} | |
end | |
def handle_info(:start_request, state) do | |
#url = "http://www.thinkbroadband.com/download/" | |
#url = "http://download.thinkbroadband.com/5MB.zip" | |
#url = "http://download.thinkbroadband.com/1GB.zip" | |
poison = HTTPoison.get!(url, %{}, [stream_to: self()]) | |
{:noreply, %{ state | poison: poison, size: 0 }} | |
end | |
def handle_info(:check_size, %{size: size} = state) when size > 10_000_000, do: {:stop, :normal, state} # file is big, lets stop now | |
def handle_info(:check_size, %{size: size} = state) do | |
IO.puts "Size: #{size}" | |
{:noreply, state} | |
end | |
def handle_info(msg, %{ file: file } = state) do | |
updated_state = | |
case msg do | |
%HTTPoison.AsyncStatus{} -> %{ state | size: 0 } | |
%HTTPoison.AsyncHeaders{} -> | |
content_length = Enum.find_value(msg.headers, fn(map) -> if Enum.member?(Tuple.to_list(map), "Content-Length"), do: elem(map, 1) end) | |
if is_nil(content_length) do | |
%{ state | size: 0 } | |
else | |
{int, _} = Integer.parse(content_length) | |
%{ state | size: int } | |
end | |
%HTTPoison.AsyncChunk{} -> | |
%{ state | file: file <> msg.chunk, size: byte_size(updated_state.file) } | |
%HTTPoison.AsyncEnd{} -> | |
%{ state | size: byte_size(file) } | |
_ -> | |
IO.inspect {:handle_info, msg} | |
%{ state | size: 0 } | |
end | |
# verify the size on the next loop | |
send(self(), :check_size) | |
{:noreply, updated_state} | |
end | |
end | |
{:ok, pid} = StreamTest.start_link |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment