When I send from js client socket.send('{"text":"111"}')
and get this on server, by websocket.JSON.Receive(ws, &data)
, data remain empty. I use "golang.org/x/net/websocket"
type (
Msg struct {
clientKey string
text string
}
NewClientEvent struct {
clientKey string
msgChan chan *Msg
}
Item struct {
text string
}
)
var (
clientRequests = make(chan *NewClientEvent, 100)
clientDisconnects = make(chan string, 100)
messages = make(chan *Msg, 100)
)
func ChatServer(ws *websocket.Conn) {
msgChan := make(chan *Msg, 100)
clientKey := time.Now().String()
clientRequests <- &NewClientEvent{clientKey, msgChan}
defer func(){ clientDisconnects <- clientKey}()
go func(){
for msg := range msgChan{
ws.Write([]byte(msg.text))
}
}()
for {
var data Item
err := websocket.JSON.Receive(ws, &data)
if err != nil {
log.Println("Error: ", err.Error())
return
}
messages <- &Msg{clientKey, data.text}
}
}
But if I try send socket.send('"text"')
and get it by this:
var data string
err := websocket.JSON.Receive(ws, &data)
if err != nil {
log.Println("Error: ", err.Error())
return
}
messages <- &Msg{clientKey, data}
everything is working.
Chances are you'll need to define your struct before you can use JSON.receive
on an object like
{ "text": "Hi" }
type socketData struct {
Text string `json:"text"`
}
Then
data := &socketData{}
websocket.JSON.receive(ws, &data)
log.Println(data.Text) // Hi
If you're going to be sending random data that you can't really define a struct for (though this is the preferred way of doing it) you can just declare an interface{}
var data map[string]interface{}
log.Println(data["text"].(string)) // Hi
http://play.golang.org/p/Jp5qKtiUGw
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With