官方get和post的代码是有问题的,1.1下运行crash,这里修改了下,贴代码
创建工程
rebar-creator create-app testCowboy
testCowboy_app.erl
-module(testCowboy_app). -behaviour(application). -export([start/2, stop/1]). -define(C_ACCEPTORS, 100). start(_StartType, _StartArgs) -> application:start(crypto), application:start(cowlib), application:start(ranch), application:start(cowboy), Routes = route_helper:get_routes(), Dispatch = cowboy_router:compile(Routes), Port = 8080, TransOpts = [{port, Port}], ProtoOpts = [{env, [{dispatch, Dispatch}]}], cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts). stop(_State) -> ok.
route_helper.erl
-module(route_helper). -export([get_routes/0]). get_routes() -> [ {'_', [ {"/get", get_handler, []}, {"/post", post_handler, []} ]} ].
get_handler.erl
-module(get_handler). -export([init/3]). -export([handle/2]). -export([terminate/3]). init(_Transport, Req, []) -> {ok, Req, undefined}. handle(Req, State) -> {Method,_} = cowboy_req:method(Req), {Val,_} = cowboy_req:qs_val(<<"test_get">>,Req), {ok, Req2} = handle_params(Method, Val, Req), {ok, Req2, State}. terminate(_Reason, _Req, _State) -> ok. %% private handle_params(<<"GET">>, undefined, Req) -> cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req); handle_params(<<"GET">>, Val, Req) -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/plain; charset=utf-8">>} ], Val, Req); handle_params(_, _, Req) -> %% Method not allowed. cowboy_req:reply(405, Req).
post_handler.erl
-module(post_handler). -export([init/3]). -export([handle/2]). -export([terminate/3]). init(_Transport, Req, []) -> {ok, Req, undefined}. handle(Req, State) -> {Method,_} = cowboy_req:method(Req), HasBody = cowboy_req:has_body(Req), {ok, Req2} = handle_params(Method, HasBody, Req), {ok, Req2, State}. terminate(_Reason, _Req, _State) -> ok. %% private handle_params(<<"POST">>, true, Req) -> {ok, PostVals, Req2} = cowboy_req:body_qs(Req), Echo = proplists:get_value(<<"echo">>, PostVals), echo(Echo, Req2); handle_params(<<"POST">>, false, Req) -> cowboy_req:reply(400, [], <<"Missing body.">>, Req); handle_params(_, _, Req) -> %% Method not allowed. cowboy_req:reply(405, Req). echo(undefined, Req) -> cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req); echo(Echo, Req) -> cowboy_req:reply(200, [ {<<"content-type">>, <<"text/plain; charset=utf-8">>} ], Echo, Req).
get的测试url
http://127.0.0.1:8080/get?test_get=b
post的测试
http://127.0.0.1:8080/post 字段echo,value随便