【发布时间】:2017-06-22 09:41:17
【问题描述】:
尝试通过 Cowboy 设置 restful API 我需要为所有方法使用一个处理程序的主要内容
这里是路由器 ::
start(_Type, _Args) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/api", handler, []},
{"/api/:id", handler, []}
]}
]),
{ok, _} = cowboy:start_clear(http, 100, [{port, 8080}], #{
env => #{dispatch => Dispatch}
}),
api_sup:start_link().
这里是处理程序代码::
-module(handler).
-export([init/3, handle/2]).
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, Opts) ->
case cowboy_req:method(Req) of
<<"POST">> ->
Body = cowboy_req:has_body(Req),
Request = postMethod(<<"POST">>, Body, Req),
{ok, Request, Opts};
<<"GET">> ->
#{id := Id} = cowboy_req:match_qs([{id, [], undefined}], Req),
Request = getMethod(<<"GET">>, Id, Req),
{ok, Request, Opts};
<<"PUT">> ->
Body = cowboy_req:has_body(Req),
Request = putMethod(<<"PUT">>, Body, Req),
{ok, Request, Opts};
<<"DELETE">> ->
#{id := Id} = cowboy_req:match_qs([{id, [], undefined}], Req),
Request = deleteMethod(<<"DELETE">>, Id, Req),
{ok, Request, Opts}
end.
postMethod(<<"POST">>, _Body, Req) ->
cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"POST\"}">>, Req).
getMethod(<<"GET">>, _Id, Req) ->
cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"GET\"}">>, Req).
putMethod(<<"PUT">>, _Body, Req) ->
cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"PUT\"}">>, Req).
deleteMethod(<<"DELETE">>, _Id, Req) ->
cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, <<"{\"status\": \"DELETE\"}">>, Req).
我收到错误:牛仔 500 错误
【问题讨论】:
-
您在启动此服务器的终端中是否遇到任何错误?
-
不,当我启动服务器时一切正常
-
从 api_app.app 中删除了啤酒,连接错误消失了。但现在我面临 500 错误
标签: rest api erlang handler cowboy