aboutsummaryrefslogtreecommitdiffstats
path: root/examples/eventsource/src/eventsource_handler.erl
diff options
context:
space:
mode:
authorAdam Cammack <[email protected]>2013-02-16 02:26:32 -0600
committerAdam Cammack <[email protected]>2013-02-16 02:26:32 -0600
commita302fe500736f3aa0dc36771db3077eb0752eebb (patch)
tree4e6a9ba989d8ab9a5d7cc988af1e21cc024279e0 /examples/eventsource/src/eventsource_handler.erl
parente3daf439da42283cf65faa3311ff73bb7ffe413b (diff)
downloadcowboy-a302fe500736f3aa0dc36771db3077eb0752eebb.tar.gz
cowboy-a302fe500736f3aa0dc36771db3077eb0752eebb.tar.bz2
cowboy-a302fe500736f3aa0dc36771db3077eb0752eebb.zip
Add EventSource example
Port from extend/cowboy_examples.
Diffstat (limited to 'examples/eventsource/src/eventsource_handler.erl')
-rw-r--r--examples/eventsource/src/eventsource_handler.erl27
1 files changed, 27 insertions, 0 deletions
diff --git a/examples/eventsource/src/eventsource_handler.erl b/examples/eventsource/src/eventsource_handler.erl
new file mode 100644
index 0000000..661057c
--- /dev/null
+++ b/examples/eventsource/src/eventsource_handler.erl
@@ -0,0 +1,27 @@
+%% Feel free to use, reuse and abuse the code in this file.
+
+%% @doc EventSource emitter.
+-module(eventsource_handler).
+
+-export([init/3]).
+-export([info/3]).
+-export([terminate/3]).
+
+init(_Transport, Req, []) ->
+ Headers = [{<<"content-type">>, <<"text/event-stream">>}],
+ {ok, Req2} = cowboy_req:chunked_reply(200, Headers, Req),
+ erlang:send_after(1000, self(), {message, "Tick"}),
+ {loop, Req2, undefined, 5000}.
+
+info({message, Msg}, Req, State) ->
+ ok = cowboy_req:chunk(["id: ", id(), "\ndata: ", Msg, "\n\n"], Req),
+ erlang:send_after(1000, self(), {message, "Tick"}),
+ {loop, Req, State}.
+
+terminate(_Reason, _Req, _State) ->
+ ok.
+
+id() ->
+ {Mega, Sec, Micro} = erlang:now(),
+ Id = (Mega * 1000000 + Sec) * 1000000 + Micro,
+ integer_to_list(Id, 16).