gpt4 book ai didi

rest - Cowboy 多方法处理器

转载 作者:行者123 更新时间:2023-12-05 01:02:24 28 4
gpt4 key购买 nike

尝试通过 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 错误

最佳答案

找到了答案。这是工作正常的代码(使用 Cowboy 的主版本)

-module(handler).

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

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

allowed_methods(Req, State) ->
{[<<"GET">>, <<"POST">>, <<"PUT">>, <<"DELETE">>], Req, State}.

content_types_provided(Req, State) ->
{[{<<"application/json">>, router}], Req, State}.

content_types_accepted(Req, State) ->
{[{<<"application/json">>, router}], Req, State}.

router(Req, Opts) ->
case cowboy_req:method(Req) of
<<"POST">> ->
{<<"{\"status\": \"POST\"}">>, Req, State};
<<"GET">> ->
{<<"{\"status\": \"GET\"}">>, Req, State};
<<"PUT">> ->
{<<"{\"status\": \"PUT\"}">>, Req, State};
<<"DELETE">> ->
{<<"{\"status\": \"DELETE\"}">>, Req, State}
end.

关于rest - Cowboy 多方法处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42050994/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com