【问题标题】:Send arbitrary JSON to gorilla websocket connection向 gorilla websocket 连接发送任意 JSON
【发布时间】:2021-01-06 22:08:45
【问题描述】:

我有以下功能,我想将任意 JSON 数据发送到 websocket 连接。数据取决于发送到服务器的内容。如果不为我要发送的每件东西创建不同的结构,如何实现这一点?

我正在考虑这样的事情:

func Register(c *websocket.Conn, m WebsocketGeneralClientMessage) {
    var d RegisterData
    json.Unmarshal(m.Data, &d)
    if len(d.Email) < 6 || len(d.Email) > 64 {
        c.WriteJSON(WebsocketGeneralServerMessage{
            Type: "error", Data: map[string]interface{"text": "This is an error"}})
        return
    }
    if len(d.Password) < 6 || len(d.Password) > 32 {
        c.WriteJSON(WebsocketGeneralServerMessage{
            Type: "error", Data: map[string]interface{"text": "This is another error"}})
        return
    }
    err := checkmail.ValidateFormat(d.Email)
    if err != nil {
        c.WriteJSON(WebsocketGeneralServerMessage{
            Type: "error", Data: map[string]interface{"text": "This is different than all the previous errors"}})
        return
    }
    uuid, email, password, err := DB.RegisterAccount(requestEmail, requestPassword)
    if err != nil {
        c.WriteJSON(WebsocketGeneralServerMessage{
            Type: "error", Data: map[string]interface{"text": "An error occured while saving the account to the database"}})
        return
    }
    c.WriteJSON(WebsocketGeneralServerMessage{
        Type: "success", Data: map[string]interface{"uuid": uuid}})
    return
}

type WebsocketGeneralServerMessage struct {
    Type string
    Data map[string]interface{}
}

但是,编译器说:

syntax error: unexpected literal "text", expecting method or interface name

所以看来这种语法是无效的。在这里可以做什么?

【问题讨论】:

  • 它是map[string]interface{}{"text": ...。你错过了{}
  • 哇!请将此添加为答案。非常感谢您的回复!那速度非常快。

标签: go gorilla


【解决方案1】:

它是map[string]interface{}{"text": ...。你错过了{}

【讨论】:

  • 这样处理json的时候,我几乎总是加type M map[string]interface{}。这使您可以使用M{"key":123,"submap":M{"abc":"def"}} 制作数据,从而使源代码更易于阅读
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
  • 2015-05-03
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 2015-09-15
相关资源
最近更新 更多