diff options
author | Adam Cammack <[email protected]> | 2013-02-10 13:54:51 -0600 |
---|---|---|
committer | Adam Cammack <[email protected]> | 2013-02-12 09:44:26 -0600 |
commit | f9dd3c9e54da7690db6f936d644c1c7b88ac6e9b (patch) | |
tree | 743c6b84d3429d163fbcaca083e3c6d211f35085 /examples/rest_stream_response/src/toppage_handler.erl | |
parent | bce7b860ee925b61fe8aa14565301c3c4aa65de2 (diff) | |
download | cowboy-f9dd3c9e54da7690db6f936d644c1c7b88ac6e9b.tar.gz cowboy-f9dd3c9e54da7690db6f936d644c1c7b88ac6e9b.tar.bz2 cowboy-f9dd3c9e54da7690db6f936d644c1c7b88ac6e9b.zip |
Add a REST example that streams its response
Diffstat (limited to 'examples/rest_stream_response/src/toppage_handler.erl')
-rw-r--r-- | examples/rest_stream_response/src/toppage_handler.erl | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/examples/rest_stream_response/src/toppage_handler.erl b/examples/rest_stream_response/src/toppage_handler.erl new file mode 100644 index 0000000..5052038 --- /dev/null +++ b/examples/rest_stream_response/src/toppage_handler.erl @@ -0,0 +1,42 @@ +%% Feel free to use, reuse and abuse the code in this file. + +%% @doc Streaming handler. +-module(toppage_handler). + +-export([init/3]). +-export([rest_init/2]). +-export([content_types_provided/2]). +-export([streaming_csv/2]). + +init(_Transport, _Req, _Table) -> + {upgrade, protocol, cowboy_rest}. + +rest_init(Req, Table) -> + {ok, Req, Table}. + +content_types_provided(Req, State) -> + {[ + {{<<"text">>, <<"csv">>, []}, streaming_csv} + ], Req, State}. + +streaming_csv(Req, Table) -> + {N, Req1} = cowboy_req:binding(v1, Req, 1), + MS = [{{'$1', '$2', '$3'}, [{'==', '$2', N}], ['$$']}], + + {{stream, result_streamer(Table, MS)}, Req1, Table}. + +result_streamer(Table, MS) -> + fun (Socket, Transport) -> + send_records(Socket, Transport, ets:select(Table, MS, 1)) + end. + +send_records(Socket, Transport, {[Rec], Cont}) -> + timer:sleep(500), + send_line(Socket, Transport, Rec), + send_records(Socket, Transport, ets:select(Cont)); +send_records(_Socket, _Transport, '$end_of_table') -> + ok. + +send_line(Socket, Transport, [Key, V1, V2]) -> + Transport:send(Socket, + [Key, $,, integer_to_list(V1), $,, integer_to_list(V2), $\r, $\n]). |