我想对地图中某个键的值进行模式匹配
def handle_in("new_message", payload, socket) do
case payload.message do
"hello" -> broadcast! socket, "new_message", payload
end
{:noreply, socket}
end
[error] GenServer #PID<0.378.0> terminating
** (KeyError) key :message not found in: %{"message" => "hello", "name" => "x"}
(chatroom) web/channels/lobby_channel.ex:9: Chatroom.LobbyChannel.handle_in/3
(phoenix) lib/phoenix/channel/server.ex:226: anonymous fn/4 in Phoenix.Channel.Server.handle_info/2
(stdlib) gen_server.erl:601: :gen_server.try_dispatch/4
(stdlib) gen_server.erl:667: :gen_server.handle_msg/5
当我发送%{"message" => "hello", "name" => "x"}
的有效负载时,会发生该错误,或者发送任何其他消息。
答案 0 :(得分:3)
此处的密钥为"message"
而不是:message
。使用:payload["message"]
def handle_in("new_message", payload, socket) do
case payload["message"] do
"hello" -> broadcast! socket, "new_message", payload
end
{:noreply, socket}
end
你也可以这样做:
def handle_in("new_message", %{"message" => message}, socket) do
case message do
# ...
end