牛仔的多个休息处理程序

Mat*_*att 2 rest erlang cowboy

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

并通过一个可以区分它们的处理程序使每个动作服务?所有示例似乎都将1个处理程序映射到1个调度,如果可能的话,我想整合功能.

P_A*_*P_A 5

你可以这样做:

调度:

...
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.
...
Run Code Online (Sandbox Code Playgroud)

在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}.
...
Run Code Online (Sandbox Code Playgroud)

等等.