登录
首页 >  Golang >  Go问答

处理未知的 JSON 响应时使用 Gorilla Libs 进行 WebSockets 绑定

来源:stackoverflow

时间:2024-03-18 11:00:33 114浏览 收藏

**处理未知 JSON 响应时使用 Gorilla Libs 进行 WebSockets 绑定** 在使用 Gorilla Libs 连接到 WebSockets 时,处理未知 JSON 响应可能是一个挑战。为了过滤掉不需要的响应,可以采用以下方法: * **解析 JSON 结构:**使用自动 JSON 到 Go 结构工具,尝试将 JSON 响应解析为特定结构。如果工具遇到错误,则表明响应与预期结构不匹配。 * **比较元素数量:**仔细观察 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 消息,所以不能只写一个结构。

一个 websocket 的例子,我知道我不需要,因为我想忽略许多其他的:

[  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: persistent:false template:#remote-avatar] datatype:u from_session_id:f6ee84ab-15af-4bc0-b9df-aa9c71093118]]

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

ideal:如果我可以以某种方式动态搜索界面,并且如果 json 是我期望的,那么将其放入结构中的对象中......或类似的......

谢谢

[编辑]

我需要忽略的差异示例:

[  channel:zramdon naf map[data:map[components:map[0:map[x:4.001814822517539 y:2.644030847036413 z:30.97952900553247] 1:map[x:2.4521572390556376e-13 y:-14.000000000000105 z:8.633353546977925e-15] 10:map[x:0 y:0 z:0] 11:map[x:0 y:0 z:0] 12:false 2:map[x:1 y:1.0000000000000715 z:1.0000000000000009] 3:map[avatarsrc:https://somesite.com/api/v1/avatars/3iadk9x/avatar.gltf?v=63743924756 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:-7.540983606551728 y:111.09374999994142 z:-4.904411738530524e-11] 7:map[x:0 y:0 z:0] 8:map[x:0 y:0 z:0] 9:false] creator:de96a126-cf5f-48b2-8c0c-02d79b4382d5 isfirstsync:true lastownertime:1.5934383934451e+12 networkid:5jwrz57 owner:de96a126-cf5f-48b2-8c0c-02d79b4382d5 parent: persistent:false template:#remote-avatar] datatype:u from_session_id:de96a126-cf5f-48b2-8c0c-02d79b4382d5]]

另一个:

[  phoenix phx_reply map[response:map[] status:ok]]

另一个这个是我得到的最多的一个,但我不需要,所以需要将其全部过滤掉:

[  channel:zramdon naf map[data:map[components:map[0:map[x:4.001814822517539 y:2.644030847036413 z:30.97952900553247] 1:map[x:2.4521572390556376e-13 y:-14.000000000000105 z:8.633353546977925e-15] 10:map[x:0 y:0 z:0] 11:map[x:0 y:0 z:0] 12:false 2:map[x:1 y:1.0000000000000715 z:1.0000000000000009] 3:map[avatarsrc:https://somesite.com/api/v1/avatars/3iadk9x/avatar.gltf?v=63743924756 avatartype:skinnable muted:true] 4:map[left_hand_pose:0

那些和类似 100 个其他的甚至更加不同,甚至不一样的模式,如果它们具有所有相同的模式但不同的内容,那么编写一个结构并了解 json 文档将很容易。

这是我真正需要的:

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

所以我需要以某种方式获得过滤器/摆脱,然后从这个响应中我可以编写一个结构来放入 null、null、通道、消息等

感谢您的帮助。这让我发疯

编辑2:

好的,我已经打开 chrome 开发工具的 websocket 网络选项卡: 我注意到总是有一个包含 4 个元素的数组,然后在末尾打开一个 json 。但这个 json 始终是 diff,并且到目前为止的解密是模糊的:

["2", "238", "hub:zwxk8u6", "nafr", {,…}]
0: "2"
1: "238"
2: "room:zramdon"
3: "nafr"
4: {,…}
naf: "{"datatype":"um","data":{"d":[{"networkid":"a8afc029-a3af-459b-ac89-83557814deac","owner":"fa477e9d-7e92-4c1d-9b7b-6e9e0e975495","creator":"","lastownertime":1593446129608,"template":"#static-controlled-media","persistent":true,"parent":null,"components":{"1":169.509434}}]}}"

另一个类似但在 3 个元素上有所不同的:

"2", "237", "room:zramdon", "naf",…]
0: "2"
1: "237"
2: "room:zramdon"
3: "naf"
4: {datatype: "u", data: {networkid: "mi2p4c5", owner: "fa477e9d-7e92-4c1d-9b7b-6e9e0e975495",…}}
data: {networkid: "mi2p4c5", owner: "fa477e9d-7e92-4c1d-9b7b-6e9e0e975495",…}
components: {0: {x: -0.4637117156600495, y: 2.255, z: 8.3544556410586}, 1: {x: 0, y: -14.000000000000009, z: 0},…}
0: {x: -0.4637117156600495, y: 2.255, z: 8.3544556410586}
1: {x: 0, y: -14.000000000000009, z: 0}
2: {x: 1, y: 1, z: 1}
3: {,…}
4: {left_hand_pose: 0, right_hand_pose: 0}
5: {x: 0, y: 1.6, z: 0}
6: {x: 0, y: 0, z: 0}
7: {x: 0, y: 0, z: 0}
8: {x: 0, y: 0, z: 0}
9: false
10: {x: 0, y: 0, z: 0}
11: {x: 0, y: 0, z: 0}
12: false
creator: "fa477e9d-7e92-4c1d-9b7b-6e9e0e975495"
isfirstsync: true
lastownertime: 1593446133299
networkid: "mi2p4c5"
owner: "fa477e9d-7e92-4c1d-9b7b-6e9e0e975495"
parent: null
persistent: false
template: "#remote-avatar"
datatype: "u"

还有一个例子:

[null, "235", "phoenix", "heartbeat", {}]
0: null
1: "235"
2: "phoenix"
3: "heartbeat"
4: {}

以及我真正需要的:

[null, null, "room:zramdon", "message", {session_id: "fa477e9d-7e92-4c1d-9b7b-6e9e0e975495",…}]
0: null
1: null
2: "room:zramdon"
3: "message"
4: {session_id: "fa477e9d-7e92-4c1d-9b7b-6e9e0e975495",…}
body: "testtttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"
session_id: "fa477e9d-7e92-4c1d-9b7b-6e9e0e975495"
type: "chat"

很明显,有一个包含 5 个元素的 json 数组,问题出在元素 3 之后。我尝试将所有这些解析为自动 json to go struct 工具,甚至该工具也会感到困惑并吐出错误。

好吧,所以我不确定我在做什么,但我已将 3 个 diff json 输出合并为一个,如下所示:

type WebSocketHubs []WebSocketHubElement

type WebSocketHubClass struct {
    SessionID string `json:"session_id"`
    Body      string `json:"body"`
    Type      string `json:"type"`
    DataType  string `json:"dataType"`
    Data      Data   `json:"data"`
}

type WebSocketHubElement struct {
    String            *string
    WebSocketHubClass *WebSocketHubClass
}

type Data struct {
    NetworkID     string                     `json:"networkId"`
    Owner         string                     `json:"owner"`
    Creator       string                     `json:"creator"`
    LastOwnerTime int64                      `json:"lastOwnerTime"`
    Template      string                     `json:"template"`
    Persistent    bool                       `json:"persistent"`
    Parent        interface{}                `json:"parent"`
    Components    map[string]*ComponentValue `json:"components"`
    IsFirstSync   bool                       `json:"isFirstSync"`
}

type ComponentClass struct {
    X             *float64 `json:"x,omitempty"`
    Y             *float64 `json:"y,omitempty"`
    Z             *float64 `json:"z,omitempty"`
    AvatarSrc     *string  `json:"avatarSrc,omitempty"`
    AvatarType    *string  `json:"avatarType,omitempty"`
    Muted         *bool    `json:"muted,omitempty"`
    LeftHandPose  *int64   `json:"left_hand_pose,omitempty"`
    RightHandPose *int64   `json:"right_hand_pose,omitempty"`
}

type ComponentValue struct {
    Bool           *bool
    ComponentClass *ComponentClass
}

但现在我得到:

读取错误:json:无法将字符串解组为 main.websockethubclass 类型的 go 值

:(


解决方案


好吧,所以我厌倦了没有帮助和没有明确的文档,只是采用了暴力方法并使用对数组和映射的调用,然后比较字符串以获得我需要的内容。

var leerCHAT []interface{}

    for {
        //line, message, err := ws.ReadMessage()
        err := ws.ReadJSON(&leerCHAT)

        if err != nil {
            log.Printf("Error read: %s", err)
            break
        }
        log.Printf("Message received: %v", leerCHAT[2])
        if leerCHAT[3] == "message" {
            //var cookie string
            cookie := leerCHAT[4].(map[string]interface{})
            log.Printf("el chat dice: %s", cookie["body"].(string))
            chatMSG := cookie["body"].(string)
            go MatrixSay(matrixClient, chatMSG, matrixChannel)

        }

    }

我在另一个问题的帮助下改变了这一点,我遇到了另一个问题,但最终重构了整个事情。 Whats the best way to get content from a generic and somehow dynamic go map?

理论要掌握,实操不能落!以上关于《处理未知的 JSON 响应时使用 Gorilla Libs 进行 WebSockets 绑定》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>