Cowboy 中的多个休息处理程序

Multiple rest handlers in Cowboy

是否有一种简单的方法可以在 Cowboy 中设置允许多个处理程序的单个调度路由,例如: /base/add_something /base/remove_something

并让每个操作都由可以区分它们的单个处理程序提供服务?所有示例似乎都将 1 个处理程序映射到 1 个调度,如果可能的话,我想合并功能。

你可以这样做:

调度:

...
Dispatch = cowboy_router:compile(
             [{'_', [{"/base/:action", 
                      [{type,
                        function,
                        is_in_list([<<"add_something">>,
                                    <<"remove_something">>])}], 
                      app_handler, []}]}]),
...
is_in_list(L) ->
    fun(Value) -> lists:member(Value, L) end.
...

在app_handler.erl中:

...
-record(state, {action :: binary()}).
...
rest_init(Req, Opts) ->
    {Action, Req2} = cowboy_req:binding(action, Req),
    {ok, Req2, #state{action=Action}}.
...
allowed_methods(Req, #state{action=<<"add_something">>}=State) ->
    {[<<"POST">>], Req, State};
allowed_methods(Req, #state{action=<<"remove_something">>}=State) ->
    {[<<"DELETE">>], Req, State}.
...

等等。

您也可以像这样尝试使用 cowboy_rest:

content_types_accepted(Req, State) ->
   case cowboy_req:method(Req) of
     {<<"POST">>, _ } ->
       Accepted = {[{<<"application/json">>, post_json}], Req, State};
     {<<"PUT">>, _ } ->
       Accepted = {[{<<"application/json">>, put_json}], Req, State}
   end,
Accepted.