http_body_qs.erl 989 B

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