The Problem
I need some help working with types in Golang, I get super confused. I am trying to alter the websocket chat example from Gorilla, and I want to pass in JSON and process it accordingly. I need to be able to set for example a user, and send a message to the websocket.
In the current implementation all it does is receive a string, and relays it back by broadcasting it to all connected clients.
For example I want to be able to set a data structure as follows and process it differently.
Incoming user would be:
{
'type': "user",
'value': "John Doe"
}
Incomming message would be:
{
'type': "message",
'value': "Hi There, how are you?"
}
Please refer to the following code: https://github.com/gorilla/websocket/blob/master/examples/chat/conn.go#L52
for {
_, message, err := c.ws.ReadMessage()
if err != nil {
break
}
h.broadcast <- message
}
Data
So the above code works for single strings, because all the server does is pass the incoming message from any client to all. But I want to be able to save users, and send the list of active users back to the client along with the new message.
To do this, in my mind I will need to handle the different incoming messages differently. I tried to unmarchal the incomming message
, but when I print out the type it's this:
2015/11/24 20:03:10 []uint8
THE QUESTION
How do I go about reading this input stream, and unmarshal it to JSON? This is the debugging I added to the section:
for {
_, dataString, err := c.ws.ReadMessage()
if err != nil {
break
}
log.Println(reflect.TypeOf(dataString))
var data MessageData
err = json.Unmarshal(dataString, &data)
log.Println(data.Type)
log.Println(data.Value)
if err != nil {
log.Println(err)
}
h.broadcast <- dataString
}
Which Returns
2015/11/24 20:03:10 []uint8
2015/11/24 20:03:10
2015/11/24 20:03:10