aboutsummaryrefslogtreecommitdiffstats
path: root/examples/eventsource/src/eventsource_handler.erl
blob: fec2516ed997420cdb818c7dbde6b749cc9a8677 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
%% Feel free to use, reuse and abuse the code in this file.

%% @doc EventSource emitter.
-module(eventsource_handler).

-export([init/2]).
-export([info/3]).

init(Req, Opts) ->
	cowboy_req:stream_reply(200, #{
		<<"content-type">> => <<"text/event-stream">>
	}, Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{cowboy_loop, Req, Opts, 5000}.

info({message, Msg}, Req, State) ->
	cowboy_req:stream_body(["id: ", id(), "\ndata: ", Msg, "\n\n"], nofin, Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{ok, Req, State}.

id() ->
	integer_to_list(erlang:unique_integer([positive, monotonic]), 16).