发送任意 JSON 到大猩猩 websocket 连接
Send arbitrary JSON to gorilla websocket connection
我有以下功能,我想将任意 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": ...
。你错过了 {}
.
我有以下功能,我想将任意 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": ...
。你错过了 {}
.