Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get json data on go websocket server

Tags:

json

websocket

go

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.

like image 553
Samuel Loog Avatar asked Oct 17 '25 01:10

Samuel Loog


1 Answers

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

like image 111
Datsik Avatar answered Oct 19 '25 23:10

Datsik