我正在使用 Go 中的 websockets 编写一个聊天应用程序。
将有多个聊天室,想法是将连接到聊天室的所有 websocket 存储在 Redis 列表中。
为了在 Redis 中存储和检索 websockets,我必须对它们进行编码/解码,并且(根据 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())
}
}
但是,我收到了这个错误:
不能在 gob.NewEncoder 的参数中使用 ws(类型 *websocket.Conn)作为 io.Writer 类型:
*websocket.Conn 没有实现 io.Writer(缺少 Write 方法)
有 websocket.write(int, time.Time, ...[]byte) 错误
想要 Write([]byte) (int, error)
这个错误是什么意思?编码 *websocket.Conn
的整个想法是错误的还是需要类型转换?
最佳答案
As detailed in the documentation , gob.NewEncoder
的参数是要写入编码结果的 io.Writer
。这将返回一个编码器,您将要编码的对象传递给该编码器。它将对对象进行编码并将结果写入编写器。
假设 conn
是您的 redis 连接,您需要这样的东西:
buff := new(bytes.Buffer)
err := gob.NewEncoder(buff).Encode(ws)
if err != nil {
// handle error
}
_,err := conn.Do("RPUSH", room, buff.Bytes())
关于go - 使用 gob 在 Go 中编码 websockets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45943414/