go - Golang Websocket 自定义 JSON 消息
问题描述
我正在尝试发送/接收自定义 JSON 消息。JSON结构发生变化的情况有3种,因此我有3种不同的结构。我必须访问作为 RawMessage 发送的房间字符串。我的问题是频道广播应该是什么类型?
type Message struct {
Type int64 `json:"type"`
Msg json.RawMessage
}
Broadcast chan interface{} // ??? RawMessage or maybe interface
case m := <-r.Broadcast:
// What type should chan Broadcast be?
// If m is of type json.RawMessage should I deal with unmarshalling here?
connections := r.Clients[m.Room] //
for c := range connections {
select {
case c.send <- m:
default:
close(c.send)
delete(connections, c)
if len(connections) == 0 {
delete(r.Clients, m.Room)
}
}
}
for {
msg := &Message{}
err := c.conn.ReadJSON(&msg)
// _, msg, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
if msg.Type == 0 {
newVideo := &NewVideo{}
if err = json.Unmarshal(msg.Msg, &newVideo); err != nil {
fmt.Println(err)
}
Roomb.Broadcast <- msg.Msg // ??? should i send the RawMessage
online[msg.Room] = msg
} else if msg.Type == 1 {
if _, ok := online[msg.Room]; ok {
online[msg.Room].Start = float64(time.Now().Unix() - online[msg.Room].Timestamp)
c.send <- online[msg.Room]
}
} else if msg.Type == 2 {
Roomb.Broadcast <- msg.Msg // ??? should i send the RawMessage
}
fmt.Println(msg)
}
解决方案
去掉前面的“&”
msg
。msg
已经是一个指针。这可能会产生问题。你的问题不是很清楚。如果
msg.Type
定义了msg.Msg
是什么,那么我建议您使用实际消息类型输入通道,解析msg.Msg
,然后通过通道发送它。
推荐阅读
- java - 如何从每个逗号分隔行中读取前两个单词和后两个单词?
- flutter - 使用颤振时 Azure Devops 中出现奇怪的构建错误
- python - 正确匹配html解析后正确转义循环
- javascript - 只刷新一个部分(不是整个页面)
- php - Laravel PHPUNIT 你如何测试查询请求
- ssrs-2008 - SSRS 表达式在行和列中拆分字符串
- php - 附加用户实体时,用户名的 UniqueEntity 不起作用
- bookdown - bookdown 定理中的 Latex 宏
- elasticsearch - ElasticSearch 仅返回文档的特定部分
- javascript - 根据另一个对象数组替换键