Golang Websocket自定义JSON消息

Golang Websocket自定义JSON消息,go,gorilla,Go,Gorilla,我正在尝试发送/接收自定义JSON消息。JSON结构发生变化的情况有3种,因此我有3种不同的结构。我必须访问作为消息发送的房间字符串。我的问题是频道广播应该是什么类型 type Message struct { Type int64 `json:"type"` Msg json.RawMessage } 广播信道接口{}/???RawMessage或接口 case m := <-r.Broadcast: // What typ

我正在尝试发送/接收自定义JSON消息。JSON结构发生变化的情况有3种,因此我有3种不同的结构。我必须访问作为消息发送的房间字符串。我的问题是频道广播应该是什么类型

type Message struct {
    Type int64 `json:"type"`
    Msg  json.RawMessage
}
广播信道接口{}/???RawMessage或接口

          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)
                    }
                }
            }
案例m:=
  • 删除
    msg
    之前的“&”
    msg
    已经是指针。这可能会产生问题

  • 你的问题不是很清楚。如果
    msg.Type
    定义了
    msg.msg
    是什么,那么我建议您使用实际的消息类型键入频道,解析
    msg.msg
    ,然后通过频道发送

  • 删除
    msg
    之前的“&”
    msg
    已经是指针。这可能会产生问题

  • 你的问题不是很清楚。如果
    msg.Type
    定义了
    msg.msg
    是什么,那么我建议您使用实际的消息类型键入频道,解析
    msg.msg
    ,然后通过频道发送


  • 但是有3种情况下消息类型struct会发生变化。如果我将频道设置为“Struct1”类型,它将无法接受“Struct2”或“Struct3”的消息。我说的是将频道设置为非“channel”。根据需要制作尽可能多的频道。使用select语句收听所有消息,但有3种情况下消息类型struct会发生更改。如果我将频道设置为“Struct1”类型,它将无法接受“Struct2”或“Struct3”的消息。我说的是将频道设置为非“channel”。根据需要制作尽可能多的频道。使用select语句听所有这些语句
    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)
        }