http_body_qs.erl 924 B

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