http_stream_body.erl 796 B

1234567891011121314151617181920212223242526
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. -module(http_stream_body).
  3. -export([init/2]).
  4. -export([handle/2]).
  5. init(Req, Opts) ->
  6. {http, Req, Opts}.
  7. handle(Req, State) ->
  8. Body = proplists:get_value(body, State, "http_handler_stream_body"),
  9. Reply = proplists:get_value(reply, State),
  10. SFun = fun(Socket, Transport) -> Transport:send(Socket, Body) end,
  11. Req2 = case Reply of
  12. set_resp ->
  13. SLen = iolist_size(Body),
  14. cowboy_req:set_resp_body_fun(SLen, SFun, Req);
  15. set_resp_close ->
  16. cowboy_req:set_resp_body_fun(SFun, Req);
  17. set_resp_chunked ->
  18. %% Here Body should be a list of chunks, not a binary.
  19. SFun2 = fun(SendFun) -> lists:foreach(SendFun, Body) end,
  20. cowboy_req:set_resp_body_fun(chunked, SFun2, Req)
  21. end,
  22. {ok, cowboy_req:reply(200, Req2), State}.