- Notifications
You must be signed in to change notification settings - Fork0
A minimal and idiomatic WebSocket library for Go
License
go-works/websocket
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
websocket is a minimal and idiomatic WebSocket library for Go.
go get nhooyr.io/websocket@v1.1.0
- Minimal and idiomatic API
- Tiny codebase at 1700 lines
- First class context.Context support
- Thorough tests, fully passes theautobahn-testsuite
- Zero dependencies outside of the stdlib for the core library
- JSON and ProtoBuf helpers in the wsjson and wspb subpackages
- Highly optimized by default
- Concurrent writes out of the box
- WebSockets over HTTP/2#4
For a production quality example that shows off the full API, see theecho example on the godoc. On github, the example is atexample_echo_test.go.
http.HandlerFunc(func (w http.ResponseWriter,r*http.Request) {c,err:=websocket.Accept(w,r, websocket.AcceptOptions{})iferr!=nil {// ...}deferc.Close(websocket.StatusInternalError,"the sky is falling")ctx,cancel:=context.WithTimeout(r.Context(),time.Second*10)defercancel()varvinterface{}err=wsjson.Read(ctx,c,&v)iferr!=nil {// ...}log.Printf("received: %v",v)c.Close(websocket.StatusNormalClosure,"")})
The client side of this library requires at minimum Go 1.12 as it uses anew featurein net/http to perform WebSocket handshakes.
ctx,cancel:=context.WithTimeout(context.Background(),time.Minute)defercancel()c,_,err:=websocket.Dial(ctx,"ws://localhost:8080", websocket.DialOptions{})iferr!=nil {// ...}deferc.Close(websocket.StatusInternalError,"the sky is falling")err=wsjson.Write(ctx,c,"hi")iferr!=nil {// ...}c.Close(websocket.StatusNormalClosure,"")
- A minimal API is easier to maintain due to less docs, tests and bugs
- A minimal API is also easier to use and learn
- Context based cancellation is more ergonomic and robust than setting deadlines
- 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 hooksand configurations like other WebSocket libraries
- We do not support the deflate compression extension because Go's compress/flate libraryis very memory intensive and browsers do not handle WebSocket compression intelligently.See#5
Before the comparison, I want to point out that both gorilla/websocket and gobwas/ws wereextremely useful in implementing the WebSocket protocol correctly sobig thanks to theauthors of both. In particular, I made sure to go through the issue tracker of gorilla/websocketto ensure I implemented details correctly and understood how people were using WebSockets inproduction.
https://github.com/gorilla/websocket
This package is the community standard but it is 6 years old and over timehas accumulated cruft. There are too many ways to do the same thing.Just compare the godoc ofnhooyr/websocket side by side withgorilla/websocket.
The API for nhooyr/websocket has been designed such that there is only one way to do thingswhich makes it easy to use correctly. Not only is the API simpler, the implementation isonly 1700 lines whereas gorilla/websocket is at 3500 lines. That's more code to maintain,more code to test, more code to document and more surface area for bugs.
The future of gorilla/websocket is also uncertain. Seegorilla/websocket#370.
Moreover, nhooyr/websocket has support for newer Go idioms such as context.Context andalso uses net/http's Client and ResponseWriter directly for WebSocket handshakes.gorilla/websocket writes its handshakes to the underlying net.Conn which meansit has to reinvent hooks for TLS and proxies and prevents support of HTTP/2.
Some more advantages of nhooyr/websocket are that it supports concurrent writes andmakes it very easy to close the connection with a status code and reason.
nhooyr/websocket also responds to pings, pongs and close frames in a separate goroutine so thatyour application doesn't always need to read from the connection unless it expects a data message.gorilla/websocket requires you to constantly read from the connection to respond to control frameseven if you don't expect the peer to send any messages.
In terms of performance, the differences depend on your application code. nhooyr/websocketreuses buffers efficiently out of the box if you use the wsjson and wspb subpackages whereasgorilla/websocket does not. As mentioned above, nhooyr/websocket also supports concurrentwriters out of the box.
The only performance con to nhooyr/websocket is that uses two extra goroutines. One forreading pings, pongs and close frames async to application code and another to supportcontext.Context cancellation. This costs 4 KB of memory which is cheap comparedto the benefits.
https://godoc.org/golang.org/x/net/websocket
Unmaintained and the API does not reflect WebSocket semantics. Should never be used.
This library has an extremely flexible API but that comes at the cost of usabilityand clarity.
This library is fantastic in terms of performance. The author put in significanteffort to ensure its speed and I have applied as many of its optimizations asI could into nhooyr/websocket. Definitely check out his fantasticblog postabout 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 justas performant but much easier to use correctly and idiomatic.
About
A minimal and idiomatic WebSocket library for Go
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Languages
- Go94.9%
- Shell3.6%
- Dockerfile1.2%
- HCL0.3%