toppage_h.erl 828 B

1234567891011121314151617181920212223242526272829
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. %% @doc POST echo handler.
  3. -module(toppage_h).
  4. -export([init/2]).
  5. init(Req0, Opts) ->
  6. Method = cowboy_req:method(Req0),
  7. HasBody = cowboy_req:has_body(Req0),
  8. Req = maybe_echo(Method, HasBody, Req0),
  9. {ok, Req, Opts}.
  10. maybe_echo(<<"POST">>, true, Req0) ->
  11. {ok, PostVals, Req} = cowboy_req:read_urlencoded_body(Req0),
  12. Echo = proplists:get_value(<<"echo">>, PostVals),
  13. echo(Echo, Req);
  14. maybe_echo(<<"POST">>, false, Req) ->
  15. cowboy_req:reply(400, [], <<"Missing body.">>, Req);
  16. maybe_echo(_, _, Req) ->
  17. %% Method not allowed.
  18. cowboy_req:reply(405, Req).
  19. echo(undefined, Req) ->
  20. cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
  21. echo(Echo, Req) ->
  22. cowboy_req:reply(200, #{
  23. <<"content-type">> => <<"text/plain; charset=utf-8">>
  24. }, Echo, Req).