switch_handler_h.erl 872 B

123456789101112131415161718192021222324252627282930313233343536
  1. -module(switch_handler_h).
  2. -export([init/2]).
  3. -export([content_types_provided/2]).
  4. -export([provide/2]).
  5. -export([info/3]).
  6. init(Req, State) ->
  7. {cowboy_rest, Req, State}.
  8. content_types_provided(Req, State) ->
  9. {[{<<"text/plain">>, provide}], Req, State}.
  10. provide(Req0, run) ->
  11. Req = cowboy_req:stream_reply(200, Req0),
  12. send_after(0),
  13. {{switch_handler, cowboy_loop}, Req, 0};
  14. provide(Req0, hibernate) ->
  15. Req = cowboy_req:stream_reply(200, Req0),
  16. send_after(0),
  17. {{switch_handler, cowboy_loop, hibernate}, Req, 0}.
  18. send_after(N) ->
  19. erlang:send_after(100, self(), {stream, msg(N)}).
  20. msg(0) -> <<"Hello\n">>;
  21. msg(1) -> <<"streamed\n">>;
  22. msg(2) -> <<"world!\n">>;
  23. msg(3) -> stop.
  24. info({stream, stop}, Req, State) ->
  25. {stop, Req, State};
  26. info({stream, What}, Req, State) ->
  27. cowboy_req:stream_body(What, nofin, Req),
  28. send_after(State + 1),
  29. {ok, Req, State + 1}.