【问题标题】:Multiple rest handlers in Cowboy牛仔中的多个休息处理程序
【发布时间】:2015-04-18 14:37:33
【问题描述】:

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

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

【问题讨论】:

    标签: rest erlang cowboy


    【解决方案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}.
    ...
    

    等等。

    【讨论】:

    • 非常感谢,这样就可以了。似乎首选方法是单独的处理程序模块,但现在我可以选择。赞赏。
    【解决方案2】:

    你也可以尝试像这样使用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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-22
      • 2017-06-14
      • 2013-12-19
      • 2016-07-19
      • 2013-05-30
      • 2017-11-29
      • 2015-11-03
      • 2018-08-28
      相关资源
      最近更新 更多