Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Streaming Size Check
defmodule StreamTest do
use GenServer
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, :ok, opts)
end
def init(:ok) 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()])
{:ok, %{file: "", poison: poison}}
end
def handle_info(msg, %{ file: file } = state) do
updated_state = state
case msg do
%HTTPoison.AsyncStatus{} ->
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
0
else
{int, _} = Integer.parse(content_length)
int
end
%HTTPoison.AsyncChunk{} ->
updated_state = %{ state | file: file <> msg.chunk}
byte_size(updated_state.file)
%HTTPoison.AsyncEnd{} ->
byte_size(file)
_ ->
IO.inspect {:handle_info, msg}
0
end |> size_check
{:noreply, updated_state}
end
defp size_check(size) when size <= 10_000_000, do: IO.puts "Size: #{size}"
defp size_check(size) when size > 10_000_000, do: GenServer.stop(self())
end
{:ok, pid} = StreamTest.start_link
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment