Golang Websocket Custom JSON-сообщения - PullRequest
1 голос
/ 11 июня 2019

Я пытаюсь отправлять / получать пользовательские сообщения JSON. Есть 3 случая, в которых изменяется структура JSON, поэтому у меня есть 3 различных структуры. Я должен получить доступ к строке комнаты, которая отправляется как RawMessage. У меня вопрос, какого типа должен быть канал Broadcast?

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

1 Ответ

0 голосов
/ 11 июня 2019
  1. Удалите «&» перед msg.msg уже указатель.Это может создать проблемы.

  2. Ваш вопрос не очень понятен.Если msg.Type определяет, что такое msg.Msg, то я рекомендую вам создать каналы, набранные с фактическим типом сообщения, проанализировать msg.Msg, а затем отправить его через канал.

...