首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向gorilla websocket连接发送任意JSON

向gorilla websocket连接发送任意JSON
EN

Stack Overflow用户
提问于 2020-09-21 01:16:26
回答 1查看 71关注 0票数 0

我有以下函数,用来向websocket连接发送任意的JSON数据。数据取决于发送到服务器的内容。如何才能做到这一点,而不是为我想要发送的每个东西创建不同的结构?

我在想这样的事情:

代码语言:javascript
复制
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
}
代码语言:javascript
复制
type WebsocketGeneralServerMessage struct {
    Type string
    Data map[string]interface{}
}

但是,编译器会说:

代码语言:javascript
复制
syntax error: unexpected literal "text", expecting method or interface name

所以看起来这个语法是无效的。这里可以做些什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-21 01:20:57

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63981670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档