| 1 |
%% Feel free to use, reuse and abuse the code in this file. |
| 2 |
|
| 3 |
%% @doc POST echo handler. |
| 4 |
-module(toppage_h). |
| 5 |
|
| 6 |
-export([init/2]). |
| 7 |
|
| 8 |
init(Req0, Opts) -> |
| 9 |
Method = cowboy_req:method(Req0), |
| 10 |
HasBody = cowboy_req:has_body(Req0), |
| 11 |
Req = maybe_echo(Method, HasBody, Req0), |
| 12 |
{ok, Req, Opts}. |
| 13 |
|
| 14 |
maybe_echo(<<"POST">>, true, Req0) -> |
| 15 |
{ok, PostVals, Req} = cowboy_req:read_urlencoded_body(Req0), |
| 16 |
Echo = proplists:get_value(<<"echo">>, PostVals), |
| 17 |
echo(Echo, Req); |
| 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 |
|
| 24 |
echo(undefined, Req) -> |
| 25 |
cowboy_req:reply(400, #{}, <<"Missing echo parameter.">>, Req); |
| 26 |
echo(Echo, Req) -> |
| 27 |
cowboy_req:reply(200, #{ |
| 28 |
<<"content-type">> => <<"text/plain; charset=utf-8">> |
| 29 |
}, Echo, Req). |