Search code examples
gogorilla

Send arbitrary JSON to gorilla websocket connection


I have the following function where I want to send arbitrary JSON data to a websocket connection. The data depends on what was sent to the server. How this can be achieved without creating different structs for each thing I want to send?

I am thinking about something like this:

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{}
}

However, the compiler says:

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

so it seems this syntax is not valid. What can be done here?


Solution

  • It's map[string]interface{}{"text": .... You missed the {}.