http_stream_body.erl 1.1 KB

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