使用 gob 在 Go 中编码 websockets

Encode websockets in Go with gob

我正在使用 Go 中的 websockets 编写一个聊天应用程序。

将有多个聊天室,想法是将连接到聊天室的所有 websockets 存储在 Redis 列表中。

为了在 Redis 中存储和检索 websockets,我必须 encode/decode 它们并且(在 this 问题之后)我认为我可以为此使用 gob。

我将 github.com/garyburd/redigo/redis 用于 Redis 并使用 github.com/gorilla/websocket 作为我的 websocket 库。

我的函数如下所示:

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())
    }
}

但是,我收到此错误:

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)

这个错误是什么意思?编码 *websocket.Conn 的整个想法是错误的还是需要类型转换?

As detailed in the documentationgob.NewEncoder 的参数是您要写入编码结果的 io.Writer。这 returns 一个编码器,您将要编码的对象传递给它。它将对对象进行编码并将结果写入写入器。

假设 conn 是你的 redis 连接,你想要这样的东西:

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