toppage_handler.erl 959 B

123456789101112131415161718192021222324252627282930313233343536
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. %% @doc POST echo handler.
  3. -module(toppage_handler).
  4. -export([init/3]).
  5. -export([handle/2]).
  6. -export([terminate/3]).
  7. init(_Transport, Req, []) ->
  8. {ok, Req, undefined}.
  9. handle(Req, State) ->
  10. {Method, Req2} = cowboy_req:method(Req),
  11. HasBody = cowboy_req:has_body(Req2),
  12. {ok, Req3} = maybe_echo(Method, HasBody, Req2),
  13. {ok, Req3, State}.
  14. maybe_echo(<<"POST">>, true, Req) ->
  15. {ok, PostVals, Req2} = cowboy_req:body_qs(Req),
  16. Echo = proplists:get_value(<<"echo">>, PostVals),
  17. echo(Echo, Req2);
  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(undefined, Req) ->
  24. cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
  25. echo(Echo, Req) ->
  26. cowboy_req:reply(200,
  27. [{<<"content-encoding">>, <<"utf-8">>}], Echo, Req).
  28. terminate(_Reason, _Req, _State) ->
  29. ok.