http_echo_body.erl 758 B

1234567891011121314151617181920212223242526272829
  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(Req, [{length, 1000000}]) of
  10. {ok, Body, Req2} -> handle_body(Req2, Body);
  11. {more, _, Req2} -> handle_badlength(Req2)
  12. end,
  13. {ok, Req3, State}.
  14. handle_badlength(Req) ->
  15. {ok, Req2} = cowboy_req:reply(413, [], <<"Request entity too large">>, Req),
  16. {ok, Req2}.
  17. handle_body(Req, Body) ->
  18. {Size, Req2} = cowboy_req:body_length(Req),
  19. Size = byte_size(Body),
  20. {ok, Req3} = cowboy_req:reply(200, [], Body, Req2),
  21. {ok, Req3}.
  22. terminate(_, _, _) ->
  23. ok.