Last active
December 2, 2018 17:47
-
-
Save joshrotenberg/e30e74edabb1dd2ca69c46627c2fa7a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 MyApp.SSERouter do | |
use Plug.Router | |
@event_delay 2000 | |
plug(:match) | |
plug(:dispatch) | |
defp send_chunk(conn) do | |
:timer.sleep(@event_delay) | |
{:ok, conn} = chunk(conn, "event: first\n") | |
{:ok, conn} = chunk(conn, "data: here we go!\n") | |
{:ok, conn} = chunk(conn, "\n") | |
send_chunk(conn, 1) | |
end | |
defp send_chunk(conn, value) do | |
:timer.sleep(@event_delay) | |
{:ok, conn} = chunk(conn, "event: number\n") | |
{:ok, conn} = chunk(conn, "data: " <> Integer.to_string(value) <> "\n") | |
{:ok, conn} = chunk(conn, "\n") | |
send_chunk(conn, value + 1) | |
end | |
get "/sse" do | |
conn | |
|> put_resp_content_type("text/event-stream") | |
|> put_resp_header("connection", "keep-alive") | |
|> put_resp_header("cache-control", "no-cache") | |
|> send_chunked(200) | |
|> send_chunk | |
end | |
get "/foo" do | |
send_resp(conn, 200, "ok!") | |
end | |
match _ do | |
send_resp(conn, 404, "oops") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment