cowboy的get和post的例子

官方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随便

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值