前端框架选型是企业提升开发效率与用户体验的关键因素
1277
2022-11-04
Go的最小和惯用的WebSocket库
websocket
websocket is a minimal and idiomatic WebSocket library for Go.
This library is not final and the API is subject to change.
If you have any feedback, please feel free to open an issue.
Install
go get nhooyr.io/websocket@v0.2.0
Features
Minimal yet pragmatic APIFirst class context.Context supportThoroughly tested, fully passes the autobahn-testsuiteConcurrent writesZero dependencies outside of the stdlib for the core libraryjsON and ProtoBuf helpers in the wsjson and wspb subpackages
Roadmap
WebSockets over HTTP/2 #4 Deflate extension support #5
Examples
For a production quality example that shows off the full API, see the echo example on the godoc. On github, the example is at example_echo_test.go.
Server
http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { c, err := websocket.Accept(w, r, websocket.AcceptOptions{}) 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, "")})
Client
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)defer cancel()c, _, err := websocket.Dial(ctx, "ws://localhost:8080", websocket.DialOptions{})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, "")
Design considerations
Minimal API is easier to maintain and learnContext based cancellation is more ergonomic and robust than setting deadlinesNo ping support because TCP keep alives work fine for HTTP/1.1 and they do not make sense with HTTP/2 (see #1)net.Conn is never exposed as WebSocket over HTTP/2 will not have a net.Conn.Using net/http's Client for dialing means we do not have to reinvent dialing hooks and configurations like other WebSocket libraries
Comparison
While I believe nhooyr/websocket has a better API than existing libraries, both gorilla/websocket and gobwas/ws were extremely useful in implementing the WebSocket protocol correctly so big thanks to the authors of both. In particular, I made sure to go through the issue tracker of gorilla/websocket to make sure I implemented details correctly and understood how people were using the package in production.
gorilla/websocket
https://github.com/gorilla/websocket
This package is the community standard but it is 6 years old and over time has accumulated cruft. Using is not clear as there are many ways to do things and there are some rough edges. Just compare the godoc of nhooyr/websocket side by side with gorilla/websocket.
The API for nhooyr/websocket has been designed such that there is only one way to do things which makes it easy to use correctly.
Furthermore, nhooyr/websocket has support for newer Go idioms such as context.Context and also uses net/http's Client and ResponseWriter directly for WebSocket handshakes. gorilla/websocket writes its handshakes to the underlying net.Conn which means it has to reinvent hooks for TLS and proxying and prevents support of HTTP/2.
Another advantage of nhooyr/websocket is that it supports concurrent writers out of the box.
x/net/websocket
https://godoc.org/golang.org/x/net/websocket
Unmaintained and the API does not reflect WebSocket semantics. Should never be used.
See https://github.com/golang/go/issues/18152
gobwas/ws
https://github.com/gobwas/ws
This library has an extremely flexible API but that comes at the cost of usability and clarity.
This library is fantastic in terms of performance. The author put in significant effort to ensure its speed and I have applied as many of its optimizations as I could into nhooyr/websocket. Definitely check out his fantastic blog post about performant WebSocket servers.
If you want a library that gives you absolute control over everything, this is the library, but for most users, the API provided by nhooyr/websocket will fit better as it is nearly just as performant but much easier to use correctly and idiomatic.
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~