dtxq82489 2015-10-28 15:42
浏览 24
已采纳

Go-编码嵌套结构

I'm working on an extension of http://gary.burd.info/go-websocket-chat.

This example sends raw text through websockets.

I want to use JSON data instead.

I did some structures in my Go code, but when I convert it to JSON to write it to the client, the nested structures are not in the result.

Some code :

type(
    ChatroomData struct {
        Token string `json:"token"`
        Chatroom *Chatroom `json:"chatroom"`
    }
    Message struct {
        Token string `json:"token,omitempty"`
        Type string `json:"type"`
        Author string `json:"author"`
        Content string `json:"content"`
        Chatroom string `json:"chatroom"`
    }
    Messages []Message
)

The chatroom struct :

Chatroom struct {
    Name string `json:"name"`
    Users []User `json:"users"`
    Messages Messages `json:"messages"`
    Hub *WsHub `json:"-"`
}
Chatrooms map[string]*Chatroom
User struct {
    username string `json:"username"`
    token string `json:"-"`
}
Users []User

Start the chatroom :

func (s *Server) startMainChatroom() {
    s.Chatrooms["main"] = &Chatroom{
        Name: "main",
        Users: make([]User, 0),
        Messages: make([]Message, 0),
        Hub: NewHub(),
    }
    go s.Chatrooms["main"].Hub.Run()
}

The way to append messages to the chatroom :

message := Message{}
json.Unmarshal([]byte(data), &message)
message.Token = ""
message.Type = "message"
chatroom.Messages = append(chatroom.Messages, message)

Send data to the client :

func (u *User) SendChatroomData(w http.ResponseWriter, c *Chatroom, status int) {
    chatroomData := ChatroomData{Token: u.token, Chatroom: c}

    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers", "accept, authorization")
    w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
    w.WriteHeader(status)
    if err := json.NewEncoder(w).Encode(&chatroomData); err != nil {
        panic(err)
    }
}

The printed result is :

{
     "token":"a638ed3ba0c30ba3d0810fc79e12a50a",
     "chatroom":{
         "name":"main",
         "users":[{},{}],
         "messages":[]
     }
}

There are two users and three messages were sent. If I use fmt.Printf("%v ", chatroom.Messages), I have the three messages correctly stored. Same for the users, data is here when I dump it.

Many things are strange :

  • Why the messages key stays empty ?
  • Why the users key doesn't, but the slice items are empty ? (solved by Mike Reedell)

Thank you for your help, don't hesitate to ask me more code if it needs to be. I hope my post isn't already too long (and not too full of english errors X)) !

  • 写回答

2条回答 默认 最新

  • douzhantao2857 2015-10-29 13:39
    关注

    The problem was totally elsewhere : The Chatroom instance I used when adding some messages wasn't bound correctly to s.Chatrooms["main"], due to my misunderstanding of pointers.

    When I marshaled s.Chatrooms["main"], the messages weren't inside !

    Ty for your help !

    I hope this will help some others go-learners :D

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答