我使用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})
如何让它工作??
如果你喜欢函数签名中的模式匹配而不是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}.
所以改成
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}.