dreamevil0002 2017-09-26 20:59
浏览 132
已采纳

Golang后端到javascript JSON解析

I am using the gorilla websocket library for golang: http://www.gorillatoolkit.org/pkg/websocket

This is the code I am using to create the websocket connection:

conn, err := upgrader.Upgrade(w, r, nil)

Having an issue with sending JSON from golang to javascript. I can get it working but have to do what seem to be unnecessary steps. Here is the basics of the golang backend that does not work:

    type clientDB struct{
         ChunksWritten int64
         ChunksRead int64
         BytesWritten   int64
         BytesRead    int64
         DataBytesWritten int64
         DataBytesRead    int64
         ActivePeers   int
         TotalPeers    int
         TorrentHashString string
}

fullClientDB := new(clientDB) //creating a new clientDB struct

b, err := json.Marshal(fullClientDB)
        if err != nil {
            fmt.Println(err)
            return
        }


conn.WriteJSON(b)

When I use JSON.parse in javascript I get the following response:

var clientUpdate = JSON.parse(evt.data);

eyJDaHVua3NXcml0dGVuIjowLCJDaHVua3NSZWFkIjowLCJCeXRlc1dyaXR0ZW4iOjU0NDgxLCJCeXRlc1JlYWQiOjc4NzgyLCJEYXRhQnl0ZXNXcml0dGVuIjowLCJEYXRhQnl0ZXNSZWFkIjowLCJBY3RpdmVQZWVycyI6MCwiVG90YWxQZWVycyI6NDMsIlRvcnJlbnRIYXNoU3RyaW5nIjoiOWY5MTY1ZDlhMjgxYTliOGU3ODJjZDUxNzZiYmNjODI1NmZkMTg3MSJ9

I can get it working making the following changes:

conn.WriteJSON(string(b))

Then in javascript I actually parse the data TWICE.

var clientUpdate = JSON.parse(evt.data);
var clientUpdateJSON = JSON.parse(clientUpdate);

After that I can access the data correctly as a JSON object. Is there something I'm missing about sending JSON objects from golang to javascript over websockets?

  • 写回答

1条回答 默认 最新

  • duan051347 2017-09-26 21:22
    关注

    The gorilla websocket package automatically encodes to JSON so using the standard library to encode as well was just encoding it twice, causing it to show up as base64.

    Thanks guys!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格