- Notifications
You must be signed in to change notification settings - Fork0
Minimal and idiomatic WebSocket library for Go
License
jferrl/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
- Minimal and idiomatic API
- Tiny codebase at 2200 lines
- First classcontext.Context support
- Thorough tests, fully passes theautobahn-testsuite
- Zero dependencies
- JSON and ProtoBuf helpers in thewsjson andwspb subpackages
- Highly optimized by default
- Concurrent writes out of the box
- Complete Wasm support
- Close handshake
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.
Use theerrors.As functionnew in Go 1.13 to check forwebsocket.CloseError.There is alsowebsocket.CloseStatus to quickly grab the close status code out of awebsocket.CloseError.See theCloseStatus godoc example.
http.HandlerFunc(func (w http.ResponseWriter,r*http.Request) {c,err:=websocket.Accept(w,r,nil)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,"")})
ctx,cancel:=context.WithTimeout(context.Background(),time.Minute)defercancel()c,_,err:=websocket.Dial(ctx,"ws://localhost:8080",nil)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
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
The implementation of gorilla/websocket is 6 years old. As such, it iswidely used and very mature compared to nhooyr.io/websocket.
On the other hand, it has grown organically and now there are too many ways to dothe same thing. Compare the godoc ofnhooyr/websocket withgorilla/websocket side by side.
The API for nhooyr.io/websocket has been designed such that there is only one way to do things.This makes it easy to use correctly. Not only is the API simpler, the implementation isonly 2200 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.
Moreover, nhooyr.io/websocket supports newer Go idioms such as context.Context.It also uses net/http's Client and ResponseWriter directly for WebSocket handshakes.gorilla/websocket writes its handshakes to the underlying net.Conn.Thus it has to reinvent hooks for TLS and proxies and prevents support of HTTP/2.
Some more advantages of nhooyr.io/websocket are that it supports concurrent writes andmakes it very easy to close the connection with a status code and reason. In fact,nhooyr.io/websocket even implements the complete WebSocket close handshake for you whereaswith gorilla/websocket you have to perform it manually. Seegorilla/websocket#448.
The ping API is also nicer. gorilla/websocket requires registering a pong handler on the Connwhich results in awkward control flow. With nhooyr.io/websocket you use the Ping method on the Connthat sends a ping and also waits for the pong.
Additionally, nhooyr.io/websocket can compile toWasm for the browser.
In terms of performance, the differences mostly depend on your application code. nhooyr.io/websocketreuses message buffers out of the box if you use the wsjson and wspb subpackages.As mentioned above, nhooyr.io/websocket also supports concurrent writers.
The WebSocket masking algorithm used by this package is also1.75xfaster than gorilla/websocket or gobwas/ws while using only pure safe Go.
The only performance con to nhooyr.io/websocket is that it uses one extra goroutine to supportcancellation with context.Context. This costs 2 KB of memory which is cheap compared tothe 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.io/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 99.9% of use cases, nhooyr.io/websocket will fit better. It's nearly as performantbut much easier to use.
If your company or project is using this library, feel free to open an issue or PR to amend this list.
- Coder
- Tatsu Works - Ingresses 20 TB in websocket data every month on their Discord bot.
About
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
- Go98.4%
- Makefile1.1%
- Dockerfile0.5%