doucuoyan0426 2015-11-24 18:22
浏览 51

Golang处理类型

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 
  • 写回答

1条回答 默认 最新

  • donglian3055 2015-11-24 18:41
    关注

    Sorry, I was being a bit stupid with this. The message is already a byte type interface. I didn't properly encode the data on the HTML / JavaScript frontend before sending it to the backend.

    What worked was stringifying it in the frontend:

    var data = {};
    data.type = "user";
    data.value = user.val();
    conn.send(JSON.stringify(data));
    JSON.stringify(data)
    

    Then I was able to unmarshall the JSON:

    2015/11/24 20:36:04 {user fhgfhg}
    2015/11/24 20:36:04 user
    2015/11/24 20:36:04 fhgfhg
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据