[译]Go websocket 库 - nhooyr.io/websocket (gorilla/websocket 已停止维护 建议换为该库)

1,908 阅读2分钟

前言

在学习 Go 的 websocket,发现 gorilla/websocket 已经停止维护了。

Go Packages 上找到了另外一个推荐使用的 websocket 库 nhooyr.io/websocket

Github 仓库: github.com/nhooyr/webs…


websocket

websocket 是用于 Go 的极小惯用 WebSocket 库。

安装

go get nhooyr.io/websocket

亮点

路线图

  • HTTP/2 #4

示例

这是一个产品级品质的示例,展示了完整的API,查看 echo 示例

这是一个全栈示例,查看 聊天示例

服务端

http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	if err != nil {
		// ...
	}
	defer c.Close(websocket.StatusInternalError, "the sky is falling")

	ctx, cancel := context.WithTimeout(r.Context(), time.Second*10)
	defer cancel()

	var v interface{}
	err = wsjson.Read(ctx, c, &v)
	if err != nil {
		// ...
	}

	log.Printf("received: %v", v)

	c.Close(websocket.StatusNormalClosure, "")
})

客户端

ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()

c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil)
if err != nil {
	// ...
}
defer c.Close(websocket.StatusInternalError, "the sky is falling")

err = wsjson.Write(ctx, c, "hi")
if err != nil {
	// ...
}

c.Close(websocket.StatusNormalClosure, "")

比较

gorilla/websocket(已停止维护)

gorilla/websocket 的优点:

nhooyr.io/websocket 的优点:

golang.org/x/net/websocket

golang.org/x/net/webso… 也已不推荐使用 了。查看 golang/go/issues/18152

net.Conn 有助于传送给 nhooyr.io/websocket 。

gobwas/ws

gobwas/ws 拥有极其灵活的API,这样它可以用于事件驱动风格以提高性能。查看作者的 博客投稿.

无论如何,编写惯用的 Go , nhooyr.io/websocket 会更快且更简便。