1

我正在为我的 websocket 使用牛仔和 jiffy(Json 库)。我可以在我的 websocket_handle 中接收来自客户端的数据,因为现在我有与此类似的代码

websocket_handle({text, Msg}, Req, Handle) ->
    Message = jiffy:decode(Msg),
    case Message of  

       pattern1 -> ......... pattern2 -> .......... end, {ok, Res, State}

然而,我想在句柄级别进行模式匹配而不是这个......

  websocket_handle({text, pattern1}, Req, State),
  websocket_handle({text, pattern2}, Req, State)

问题是我不能在 websocket_handle 的参数中使用 jiffy:decode .. 所以我不能写类似的东西

 websocket_handle({text, jiffy:decode(Msg), Req, State})

如何让它工作??? 

4

2 回答 2

5

如果您喜欢函数签名与 case 表达式中的模式匹配,您可以将解码的消息“转发”到另一个“内部”函数。

websocket_handle({text, Msg}, Req, Handle) ->
    Message = jiffy:decode(Msg),
    websocket_handle_({test, Message}, Req, Handle).

websocket_handle_({text, Pattern1}, Req, Handle) ->
    {ok, Req, State}; 
websocket_handle_({text, Pattern2}, Req, Handle) ->
    {reply, OutFrame | [OutFrame], Req, State};
websocket_handle_({text, PatternN}, Req, Handle) ->
    {ok, Req, State}.
于 2013-06-12T06:53:06.627 回答
1

所以只需更改为

websocket_handle({text, Msg}, Req, Handle) ->
    websocket_handle_({text, jiffy:decode(Msg)}, Req, Handle).

websocket_handle_({text, Pattern1}, Req, Handle) ->
    %% do stuff,
   {ok, Req, State};
websocket_handle_({text, Pattern2}, Req, Handle) ->
    %% do stuff,
     {reply, [OutFrame], Req, State};
websocket_handle_({text, PatternN}, Req, Handle) ->
    %% do stuff,
     {reply, OutFrame, Req, State}.
于 2013-06-12T09:00:03.053 回答