牛仔和jiffy websocket_handle事件

时间:2013-06-12 05:01:15

标签: json erlang websocket cowboy

我正在使用牛仔和jiffy(Json库)作为我的websocket ..我可以在我的websocket_handle中从客户端接收数据,截至目前我的代码与此类似

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

pattern1 - >                  ...........             pattern2 - >                  ..........          结束,         {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})

如何使它工作?

2 个答案:

答案 0 :(得分:5)

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

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}.

答案 1 :(得分: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}.