cowboy使用restful的例子

直接贴代码,一切尽在不言中

%% cowboy的restful的文档,一定要好好阅读http://ninenines.eu/docs/en/cowboy/HEAD/manual/cowboy_rest/
%% 几大post提交方式https://imququ.com/post/four-ways-to-post-data-in-http.html
%% curl测试命令curl -l -H "Content-type:application/json" -X POST http://127.0.0.1:8080 -d "aaa=bbb"
-module(restful_handler).

-export([init/2]).
-export([allowed_methods/2]).
-export([content_types_provided/2]).
-export([content_types_accepted/2]).
-export([delete_completed/2]).
-export([delete_resource/2]).

-export([hello_to_html/2]).
-export([form_urlencoded_post/2]).
-export([form_data_post/2]).
-export([json_post/2]).

init(Req, Opts) ->
  {cowboy_rest, Req, Opts}.

allowed_methods(Req, State) ->
  Methods = [
    <<"HEAD">>,
    <<"GET">>,
    <<"POST">>,
    <<"PATCH">>,
    <<"DELETE">>,
    <<"OPTIONS">>
  ],
  {Methods, Req, State}.

content_types_provided(Req, State) ->
  Handlers = [
    {<<"text/html">>, hello_to_html},

    {<<"application/x-www-form-urlencoded">>, form_urlencoded_post},
    {<<"multipart/form-data">>, form_data_post},
    {<<"application/json">>, json_post}
  ],
  {Handlers, Req, State}.

content_types_accepted(Req, State) ->
  Handlers = [
    {<<"application/x-www-form-urlencoded">>, form_urlencoded_post},
    {<<"multipart/form-data">>, form_data_post},
    {<<"application/json">>, json_post}
  ],
  {Handlers, Req, State}.

delete_completed(Req, State) ->
  io:format("will delete resource~n"),
  {true, Req, State}.

delete_resource(Req, State) ->
  io:format("delete resource finish~n"),
  {true, Req, State}.

hello_to_html(Req, State) ->
  Body = <<"html">>,
  {Body, Req, State}.

form_urlencoded_post(Req, State) ->
  {ok, PostVals, _Req2} = cowboy_req:body_qs(Req),
  PostVal1 = proplists:get_value(<<"aaa">>, PostVals),
  PostVal2 = proplists:get_value(<<"bbb">>, PostVals),
  io:format("form_urlencoded_post~p~p~n",[PostVal1,PostVal2]),

  Body = string:concat(
    erlang:bitstring_to_list(PostVal1),
    erlang:bitstring_to_list(PostVal2)
  ),
  NewReq = cowboy_req:set_resp_body(erlang:list_to_bitstring(Body),Req),
  {true, NewReq, State}.

form_data_post(Req, State) ->
  {ok, PostVals, _Req2} = cowboy_req:body_qs(Req),
  PostVal = proplists:get_value(<<"aaa">>, PostVals),
  io:format("form_data_post~p~n",[PostVal]),
  NewReq = cowboy_req:set_resp_body(PostVal,Req),
  {true, NewReq, State}.

json_post(Req, State) ->
  {ok, PostVals, _Req2} = cowboy_req:body_qs(Req),
  PostVal = proplists:get_value(<<"aaa">>, PostVals),
  io:format("json_post~p~n",[PostVal]),
  NewReq = cowboy_req:set_resp_body(PostVal,Req),
  {true, NewReq, State}.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值