% 最简单的测试文件:
-module(test).
-compile(export_all).
% 打印数据
start(Ab) ->
io:format("Vsn1 (~p)",[Ab]).
% 返回一个字符串
test_str()->
X = "abc",
X.
% 测试if
test_if ( A, B ) ->
if A > B ->
io:fwrite("a~n");
B < A ->
io:fwrite("b~n");
true ->
io:fwrite("c~n")
end.
test2( En )->
case En of
<<"GET">> ->
io:fwrite("get~n");
<<"POST">> ->
io:fwrite("post~n")
end.
% 调用其它模块: 模块直接放在同级目录就可以访问到了 如:mochijson2:decode
% case 1. “中间的部分用‘;’ 结束“, 2. 最后一行不用写 3. "end." 来结束
test3( Xid ) ->
case Xid of
1 ->
% 生成数据
Mjson = {struct,
[{<<"id1">>, [<<"str1">>,<<"str2">>,<<"str3">>]},
{<<"id2">>, [<<"str4">>,<<"str5">>]}]},
Sjson = binary_to_list( list_to_binary( mochijson2:encode(Mjson)) ),
io:fwrite("~s~n",[Sjson]),
% 解出来结果,为erlang 数据结构
Mjson = mochijson2:decode(Sjson),
io:fwrite("decode:~p~n",[Mjson]);
2->
io:fwrite("case ff...~n"),
io:fwrite("case 2....~n")
end.
% end test
% 第二个测试
% post test
% curl -i -d echo=echomeplz http://localhost:8080
% get test
% http://localhost:8080/?echo=hello&name=123
%% Feel free to use, reuse and abuse the code in this file.
%% @doc GET echo handler.
-module(toppage_handler).
-export([init/2]).
init(Req, Opts) ->
Method = cowboy_req:method(Req),
%io:fwrite("me:~p",[Method]),
case Method of
<<"GET">> ->
io:fwrite("get enter...~n"),
% http://localhost:8080/?echo=hello&name=123
% 参数解析
#{echo := Echo} = cowboy_req:match_qs([echo], Req),
#{name := Name} = cowboy_req:match_qs([name], Req),
io:fwrite("ret:~p 2:~p~n",[Echo,Name]),
Req2 = echo(Method, Echo, Req),
{ok, Req2, Opts};
<<"POST">> ->
io:fwrite("post enter...~n"),
HasBody = cowboy_req:has_body(Req),
Req2 = maybe_echo(Method, HasBody, Req),
{ok, Req2, Opts}
end.
echo(<<"GET">>, undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
echo(<<"GET">>, Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], Echo, Req);
echo(_, _, Req) ->
%% Method not allowed.
cowboy_req:reply(405, Req).
% /
% /
maybe_echo(<<"POST">>, true, Req) ->
{ok, PostVals, Req2} = cowboy_req:body_qs(Req),
% 读取post 参数echo 的数据
Echo = proplists:get_value(<<"echo">>, PostVals),
io:fwrite("post get:~p~n",[Echo]),
echo_post(Echo, Req2);
maybe_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], <<"Missing body.">>, Req);
maybe_echo(_, _, Req) ->
%% Method not allowed.
cowboy_req:reply(405, Req).
echo_post(undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
echo_post(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], Echo, Req).