http_handler_body_qs.erl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. -module(http_handler_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. {error,badlength} ->
  15. echo(badlength, Req);
  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-encoding">>, <<"utf-8">>}], Echo, Req).
  31. terminate(_, _, _) ->
  32. ok.