牛仔POST处理程序

时间:2017-01-29 17:06:24

标签: rest erlang cowboy

尝试接收POST请求并将其存储到ETS表

这是代码

init(Req0, Opts) ->
    Method = cowboy_req:method(Req0),
    HasBody = cowboy_req:has_body(Req0),
    Req = maybe_echo(Method, HasBody, Req0),
    {ok, Req, Opts}.

maybe_echo(<<"POST">>, true, Req0) ->
    {ok, PostVals, Req} = cowboy_req:read_urlencoded_body(Req0),
    Echo = proplists:get_value(<<"echo">>, PostVals),
    echo(Echo, Req);

maybe_echo(<<"POST">>, false, Req) ->
    cowboy_req:reply(400, [], <<"Missing body.">>, Req);

maybe_echo(_, _, Req) ->
    %% Method not allowed.
    cowboy_req:reply(405, Req).

echo(undefined, Req) ->
    cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);

echo(Echo, Req) ->
Inf = #news{id=25, created=today, article=Echo},
    case ets:insert(news, {Inf#news.id, Inf#news.created, Inf#news.article}) of
        true -> cowboy_req:reply(200, #{<<"content-type">> => <<"text/plain; charset=utf-8">>}, Echo, Req);
        _        -> 
            Error = <<"{\"error\": \"error\"}">>,
            cowboy_req:reply(200, #{<<"content-type">> => <<"text/plain; charset=utf-8">>}, Error, Req)
    end.

当我卷曲时:

$ curl -i -H“Content-Type:application / json”-X POST -d echo ='{“action”:“insert”,“key”:“some_key”,“value”:[1, 2,3]}'http://localhost:8080/

我收到了错误:

=错误报告==== 2017年1月29日:: 18:57:21 === Ranch监听器http,连接过程&lt; 0.240.0&gt;,流1具有其请求过程&lt; 0.241.0&gt;退出,原因是badarg和stacktrace [{ets,insert,[news,{25,today,&lt;&lt;“{\”action \“:\”insert \“,\”key \“:\”some_key \“, \ “值\”:[1,2,3]} “&GT;&GT;}],[]},{post_handler,回声,2,[{文件,” E:/ _ dev的/消息/ _build /默认/ lib中/news/src/post_handler.erl"},{line,25}]},{post_handler,init,2,[{file,"e:/_dev/news/_build/default/lib/news/src/post_handler。 ERL “},{线,8}]},{cowboy_handler,执行,2,[{文件,” E:/ _ dev的/消息/ _build /默认/ LIB /牛仔/ SRC / cowboy_handler.erl“},{线, 39}]},{cowboy_stream_h,执行,3,[{文件, “E:/ _ dev的/消息/ _build /默认/ LIB /牛仔/ SRC / cowboy_stream_h.erl”},{线,173}]},{cowboy_stream_h ,proc_lib_hack,3,[{文件, “E:/ _ dev的/消息/ _build /默认/ LIB /牛仔/ SRC / cowboy_stream_h.erl”},{线,158}]},{proc_lib,init_p_do_apply,3,[{文件, “proc_lib.erl”},{线,247}]}]

但是当我像这样使用echo时:

echo(Echo, Req) ->
    cowboy_req:reply(200, #{<<"content-type">> => <<"text/plain; charset=utf-8">>}, Echo, Req)
        end.

我收到了请求 - ({“action”:“insert”,“key”:“some_key”,“value”:[1,2,3]})

看起来ETS还有什么东西?但我不知道我搞砸了哪里

在其他模块中创建ets

ets:new(news,[ordered_set,protected,named_table,{keypos,1},{read_concurrency,true},{write_concurrency,true}])

你可以告诉我解决这个问题的正确方法

1 个答案:

答案 0 :(得分:3)

protected调用中的ets:new选项意味着只允许创建ETS表的进程获得insert数据。其他进程只能读取数据。

改为使用public,所有进程都具有读/写访问权限。

相关问题