A tiny WebSocket library for Go.
RFC6455 WebSocket implementation in Go.
wsutil package, which allow
to start fast without digging the protocol internalsExisting WebSocket implementations do not allow users to reuse I/O buffers between connections in clear way. This library aims to export efficient low-level interface for working with the protocol without forcing only one way it could be used.
By the way, if you want get the higher-level tools, you can use wsutil
package.
Library is tagged as v1* so its API must not be broken during some
improvements or refactoring.
This implementation of RFC6455 passes Autobahn Test Suite and currently has about 78% coverage.
Example applications using ws are developed in separate repository
ws-examples.
The higher-level example of WebSocket echo server:
package main
import (
"net/http"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
func main() {
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, _, _, err := ws.UpgradeHTTP(r, w)
if err != nil {
// handle error
}
go func() {
defer conn.Close()
for {
msg, op, err := wsutil.ReadClientData(conn)
if err != nil {
// handle error
}
err = wsutil.WriteServerMessage(conn, op, msg)
if err != nil {
// handle error
}
}
}()
}))
}Lower-level, but still high-level example:
…We can apply the same pattern to read and write structured responses through a JSON encoder and decoder.:
...
var (
r = wsutil.NewReader(conn, ws.StateServerSide)
w = wsutil.NewWriter(conn, ws.StateServerSide, ws.OpText)
decoder = json.NewDecoder(r)
encoder = json.NewEncoder(w)
)
for {
hdr, err = r.NextFrame()
if err != nil {
return err
}
if hdr.OpCode == ws.OpClose {
return io.EOF
}
var req Request
if err := decoder.Decode(&req); err != nil {
return err
}
var resp Response
if err := encoder.Encode(&resp); err != nil {
return err
}
if err = w.Flush(); err != nil {
return err
}
}
...The lower-level example without wsutil:
…Zero-copy upgrade helps to avoid unnecessary allocations and copying while handling HTTP Upgrade request.
Processing of all non-websocket headers is made in place with use of registered user callbacks whose arguments are only valid until callback returns.
The simple example looks like this:
package main
import (
"net"
"log"
"github.com/gobwas/ws"
)
func main() {
ln, err := net.Listen("tcp", "localhost:8080")
if err != nil {
log.Fatal(err)
}
u := ws.Upgrader{
OnHeader: func(key, value []byte) (err error) {
log.Printf("non-websocket header: %q=%q", key, value)
return
},
}
for {
conn, err := ln.Accept()
if err != nil {
// handle error
}
_, err = u.Upgrade(conn)
if err != nil {
// handle error
}
}
}Usage of ws.Upgrader here brings ability to control incoming connections on
tcp level and simply not to accept them by some logic.
Zero-copy upgrade is for high-load services which have to control many resources such as connections buffers.
The real life example could be like this:
…There is a ws/wsflate package to support Permessage-Deflate Compression
Extension.
It provides minimalistic I/O wrappers to be used in conjunction with any deflate implementation (for example, the standard library's compress/flate).
It is also compatible with wsutil's reader and writer by providing
wsflate.MessageState type, which implements wsutil.SendExtension and
wsutil.RecvExtension interfaces.
…You can use compression with wsutil package this way:
…Possible incoming breakage from upstream golang
[Security] ReadFrame/ReadMessage allocate peer-declared frame length, MaxFrameSize defaults 0 -> OOM DoS (read.go:116)
Fix autobahn tests
Request: Add contribution guidelines
Provide a single callback function with all details together
change ws.Header length int64 to uint64
Reading incoming data frame with extension enabled
Keep the order of the handshake headers
report tls: first record does not look like a TLS handshake when dial with tls option
Correct way to handle continuation frame?