http_echo_body.erl 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. -module(http_echo_body).
  3. -behaviour(cowboy_http_handler).
  4. -export([init/3, handle/2, terminate/3]).
  5. init({_, http}, Req, _) ->
  6. {ok, Req, undefined}.
  7. handle(Req, State) ->
  8. true = cowboy_req:has_body(Req),
  9. {ok, Req3} = case cowboy_req:body(1000000, Req) of
  10. {error, chunked} -> handle_chunked(Req);
  11. {error, badlength} -> handle_badlength(Req);
  12. {ok, Body, Req2} -> handle_body(Req2, Body)
  13. end,
  14. {ok, Req3, State}.
  15. handle_chunked(Req) ->
  16. {ok, Data, Req2} = read_body(Req, <<>>, 1000000),
  17. {ok, Req3} = cowboy_req:reply(200, [], Data, Req2),
  18. {ok, Req3}.
  19. handle_badlength(Req) ->
  20. {ok, Req2} = cowboy_req:reply(413, [], <<"Request entity too large">>, Req),
  21. {ok, Req2}.
  22. handle_body(Req, Body) ->
  23. {Size, Req2} = cowboy_req:body_length(Req),
  24. Size = byte_size(Body),
  25. {ok, Req3} = cowboy_req:reply(200, [], Body, Req2),
  26. {ok, Req3}.
  27. terminate(_, _, _) ->
  28. ok.
  29. % Read chunked request content
  30. read_body(Req, Acc, BodyLengthRemaining) ->
  31. case cowboy_req:stream_body(Req) of
  32. {ok, Data, Req2} ->
  33. BodyLengthRem = BodyLengthRemaining - byte_size(Data),
  34. read_body(Req2, << Acc/binary, Data/binary >>, BodyLengthRem);
  35. {done, Req2} ->
  36. {ok, Acc, Req2}
  37. end.