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