Search code examples
gowebsocketgorillaredigo

Encode websockets in Go with gob


I am writing a chat application using websockets in Go.

There will be multiple chat rooms and the idea is to store all the websockets connected to a chat room in a Redis list.

In order to store and retrieve the websockets in Redis I have to encode/decode them and (following this question) I thought that I can use gob for that.

I am using github.com/garyburd/redigo/redis for Redis and github.com/gorilla/websocket as my websocket library.

My function looks like:

func addWebsocket(room string, ws *websocket.Conn) {
    conn := pool.Get()
    defer conn.Close()

    enc := gob.NewEncoder(ws)

    _, err := conn.Do("RPUSH", room, enc)
    if err != nil {
        panic(err.Error())
    }
}

However, I am getting this error:

cannot use ws (type *websocket.Conn) as type io.Writer in argument to gob.NewEncoder: *websocket.Conn does not implement io.Writer (missing Write method) have websocket.write(int, time.Time, ...[]byte) error want Write([]byte) (int, error)

What does this error mean? Is the whole idea of encoding the *websocket.Conn wrong or type conversion is required?


Solution

  • As detailed in the documentation, argument to gob.NewEncoder is the io.Writer you want the encoded result written to. This returns an encoder, to which you pass the object you want encoded. It will encode the object and write the result to the writer.

    Assuming that conn is your redis connection, you want something like:

    buff := new(bytes.Buffer)
    err := gob.NewEncoder(buff).Encode(ws)
    if err != nil {
        // handle error
    }
    _,err := conn.Do("RPUSH", room, buff.Bytes())