Skip to content

Instantly share code, notes, and snippets.

@yi-jiayu
Created February 8, 2020 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yi-jiayu/6885c524d6b31e9fb84418005160f426 to your computer and use it in GitHub Desktop.
Save yi-jiayu/6885c524d6b31e9fb84418005160f426 to your computer and use it in GitHub Desktop.
Server-sent events in Elixir with Plug
defmodule SSEDemoPlug do
use Plug.Router
plug Plug.Logger
plug(:match)
plug(:dispatch)
get "/" do
html = """
<ul></ul>
<script>
var evtSource = new EventSource('sse');
var eventList = document.querySelector('ul');
evtSource.onmessage = function(e) {
var newElement = document.createElement("li");
newElement.textContent = "message: " + e.data;
eventList.appendChild(newElement);
}
</script>
"""
conn
|> put_resp_content_type("text/html")
|> send_resp(200, html)
end
get "/sse" do
conn =
conn
|> put_resp_content_type("text/event-stream")
|> send_chunked(:ok)
~w(each chunk as a word)
|> Stream.cycle()
|> Enum.reduce_while(conn, fn chunk, conn ->
result =
case Plug.Conn.chunk(conn, "data: #{chunk}\n\n") do
{:ok, conn} ->
{:cont, conn}
{:error, :closed} ->
{:halt, conn}
end
:timer.sleep(1000)
result
end)
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