Aino.ChunkedHandler behaviour (aino v0.6.0)
Chunked Response Handler
In order to send chunked data with Aino, you must use a ChunkedHandler.
To use chunked response, you must return chunk: true
and handler: YourHandler
in the token.
EventStream Example
In the example below, a Ping route starts a chunked response.
defmodule Web.Ping do
def index(token) do
token
|> Token.response_status(200)
|> Token.response_header("Content-Type", "text/event-stream")
|> Map.put(:chunk, true)
|> Map.put(:handler, Web.Ping.Handler)
end
end
defmodule Web.Ping.Handler do
@behaviour Aino.ChunkedHandler
@impl true
def init(token) do
:timer.send_interval(1000, :ping)
{:ok, token}
end
@impl true
def handle(:ping, token) do
json = Jason.encode!(%{time: DateTime.utc_now()})
response = "event: ping
data: #{json}
"
{:ok, response, token}
end
end
Link to this section Summary
Link to this section Callbacks
Link to this callback
handle(any, t)
@callback handle(any(), Aino.Token.t()) :: {:ok, Aino.Token.t()}
Handle incoming messages
Called when any incoming messages are sent to the GenServer processing your chunked response
Link to this callback
init(t)
@callback init(Aino.Token.t()) :: {:ok, Aino.Token.t()}
Initialize your handler
Called when the chunked response initializes.