【发布时间】:2017-06-14 21:11:06
【问题描述】:
尝试接收 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 === 牧场监听器 http,连接进程 ,流 1 的请求进程 退出,原因为 badarg 和堆栈跟踪 [{ets,insert,[news,{25,today,>}],[]},{post_handler,echo, 2,[{file,"e:/_dev/news/_build/default/lib/news/src/post_handler.erl"},{line,25}]},{post_handler,init,2,[{file," e:/_dev/news/_build/default/lib/news/src/post_handler.erl"},{line,8}]},{cowboy_handler,execute,2,[{file,"e:/_dev/news/ _build/default/lib/cowboy/src/cowboy_handler.erl"},{line,39}]},{cowboy_stream_h,execute,3,[{file,"e:/_dev/news/_build/default/lib/cowboy /src/cowboy_stream_h.erl"},{line,173}]},{cowboy_stream_h,proc_lib_hack,3,[{file,"e:/_dev/news/_build/default/lib/cowboy/src/cowboy_stream_h.erl" },{line,158}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,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}])
您能否告诉我解决此问题的正确方向
【问题讨论】:
-
您如何/在哪里创建 ETS 表?你确定是
named_table并且名字是news? -
@Dogbert 我已经在像这样的启动模块中创建了它 -record(news, {id, created, article})。 Tab = ets:new(news, [ordered_set, protected, named_table, {keypos,1}, {read_concurrency, true}, {write_concurrency, true}]), {ok, Tab}。
-
@Qbeck,您应该将其编辑到问题中。