go websockets with gorilla libs - 未知的 json 响应

我是新手,我正在尝试连接到一个使用 websocket 进行许多事情的网站,包括聊天。我的目标是只获得聊天输出并对其进行处理而忽略其余部分。


我知道我期待聊天的 json,但不是其他的,所以当我运行程序时,我现在得到了所有的 websocket 输出,但我只对以下内容感兴趣:


[null,null,"channel:zRAMDON","message",{"session_id":"ramdon-d655-4ee1-ramdon","body":"TEST!!!!!!!!!!!!!!!!!!!","type":"chat"}]

现在我用来捕捉所有


var readCHAT []interface{}


go func() {

        for {

            

            err := ws.ReadJSON(&readCHAT)


            if err != nil {

                log.Printf("Error read: %s", err)

                break

            }

            log.Printf("Message received: %+v", readCHAT)

        }

    }()

我遇到的问题是我得到了 diff websocket msg,所以不能只写一个结构。


我得到一个 websocket 的例子,我不需要我想忽略的其他许多人:


[<nil> <nil> channel:zRAMDON naf map[data:map[components:map[0:map[x:18.37785615655833 y:3.849238250917483 z:31.306368728428566] 1:map[x:-2.1127290916182298e-13 y:-14.000000000000544 z:1.6920595533305515e-13] 10:map[x:0 y:0 z:0] 11:map[x:0 y:0 z:0] 12:false 2:map[x:1.0000000000000018 y:1.0000000000000713 z:0.999999999999999] 3:map[avatarSrc:https://somewhere.com/api/v1/avatars/PcJ8Sxb/avatar.gltf?v=63726570330 avatarType:skinnable muted:true] 4:map[left_hand_pose:0 right_hand_pose:0] 5:map[x:0 y:1.6 z:0] 6:map[x:5.21773538958394 y:41.12499999998135 z:-3.292556714059138e-11] 7:map[x:0 y:0 z:0] 8:map[x:0 y:0 z:0] 9:false] creator:f6ee84ab-15af-4bc0-b9df-aa9c71093118 isFirstSync:true lastOwnerTime:1.5933988881835e+12 networkId:m9ms3qv owner:f6ee84ab-15af-4bc0-b9df-aa9c71093118 parent:<nil> persistent:false template:#remote-avatar] dataType:u from_session_id:f6ee84ab-15af-4bc0-b9df-aa9c71093118]]

当我不确定我得到什么时,如果我不能将它转换为结构以使用 map[] 等,我该如何只使用我需要的 json。


理想:如果我能以某种方式动态搜索接口,并且如果 json 是我期望的,那么将它放入结构中的对象中......或类似......


谢谢


茅侃侃
浏览 103回答 1
1回答

Smart猫小萌

好的,所以我厌倦了没有帮助和清晰的文档,只是做了 brutebruce 方法并使用了对数组和映射的调用,然后比较字符串以获得我需要的东西。&nbsp; &nbsp; &nbsp; var leerCHAT []interface{}&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; //line, message, err := ws.ReadMessage()&nbsp; &nbsp; &nbsp; &nbsp; err := ws.ReadJSON(&leerCHAT)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("Error read: %s", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("Message received: %v", leerCHAT[2])&nbsp; &nbsp; &nbsp; &nbsp; if leerCHAT[3] == "message" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //var cookie string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cookie := leerCHAT[4].(map[string]interface{})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("el chat dice: %s", cookie["body"].(string))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chatMSG := cookie["body"].(string)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go MatrixSay(matrixClient, chatMSG, matrixChannel)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go