http_body_qs.erl 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. -module(http_body_qs).
  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. {Method, Req2} = cowboy_req:method(Req),
  9. HasBody = cowboy_req:has_body(Req2),
  10. {ok, Req3} = maybe_echo(Method, HasBody, Req2),
  11. {ok, Req3, State}.
  12. maybe_echo(<<"POST">>, true, Req) ->
  13. case cowboy_req:body_qs(Req) of
  14. {badlength, Req2} ->
  15. echo(badlength, Req2);
  16. {ok, PostVals, Req2} ->
  17. echo(proplists:get_value(<<"echo">>, PostVals), Req2)
  18. end;
  19. maybe_echo(<<"POST">>, false, Req) ->
  20. cowboy_req:reply(400, [], <<"Missing body.">>, Req);
  21. maybe_echo(_, _, Req) ->
  22. %% Method not allowed.
  23. cowboy_req:reply(405, Req).
  24. echo(badlength, Req) ->
  25. cowboy_req:reply(413, [], <<"POST body bigger than 16000 bytes">>, Req);
  26. echo(undefined, Req) ->
  27. cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
  28. echo(Echo, Req) ->
  29. cowboy_req:reply(200, [
  30. {<<"content-type">>, <<"text/plain; charset=utf-8">>}
  31. ], Echo, Req).
  32. terminate(_, _, _) ->
  33. ok.