Categorygithub.com/coder/websocket
modulepackage
1.8.12
Repository: https://github.com/coder/websocket.git
Documentation: pkg.go.dev

# README

websocket

Go Reference Go Coverage

websocket is a minimal and idiomatic WebSocket library for Go.

Install

go get github.com/coder/websocket

[!NOTE] Coder now maintains this project as explained in this blog post. We're grateful to nhooyr for authoring and maintaining this project from 2019 to 2024.

Highlights

Roadmap

See GitHub issues for minor issues but the major future enhancements are:

  • Perfect examples #217
  • wstest.Pipe for in memory testing #340
  • Ping pong heartbeat helper #267
  • Ping pong instrumentation callbacks #246
  • Graceful shutdown helpers #209
  • Assembly for WebSocket masking #16
    • WIP at #326, about 3x faster
  • HTTP/2 #4
  • The holy grail #402

Examples

For a production quality example that demonstrates the complete API, see the echo example.

For a full stack example, see the chat example.

Server

http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	if err != nil {
		// ...
	}
	defer c.CloseNow()

	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", nil)
if err != nil {
	// ...
}
defer c.CloseNow()

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

c.Close(websocket.StatusNormalClosure, "")

Comparison

gorilla/websocket

Advantages of gorilla/websocket:

  • Mature and widely used
  • Prepared writes
  • Configurable buffer sizes
  • No extra goroutine per connection to support cancellation with context.Context. This costs github.com/coder/websocket 2 KB of memory per connection.

Advantages of github.com/coder/websocket:

golang.org/x/net/websocket

golang.org/x/net/websocket is deprecated. See golang/go/issues/18152.

The net.Conn can help in transitioning to github.com/coder/websocket.

gobwas/ws

gobwas/ws has an extremely flexible API that allows it to be used in an event driven style for performance. See the author's blog post.

However it is quite bloated. See https://pkg.go.dev/github.com/gobwas/ws

When writing idiomatic Go, github.com/coder/websocket will be faster and easier to use.

lesismal/nbio

lesismal/nbio is similar to gobwas/ws in that the API is event driven for performance reasons.

However it is quite bloated. See https://pkg.go.dev/github.com/lesismal/nbio

When writing idiomatic Go, github.com/coder/websocket will be faster and easier to use.

# Packages

Package wsjson provides helpers for reading and writing JSON messages.

# Functions

Accept accepts a WebSocket handshake from a client and upgrades the the connection to a WebSocket.
CloseStatus is a convenience wrapper around Go 1.13's errors.As to grab the status code from a CloseError.
Dial performs a WebSocket handshake on url.
NetConn converts a *websocket.Conn into a net.Conn.

# Constants

CompressionContextTakeover compresses each message greater than 128 bytes reusing the 32 KB sliding window from previous messages.
CompressionDisabled disables the negotiation of the permessage-deflate extension.
CompressionNoContextTakeover compresses each message greater than 512 bytes.
MessageBinary is for binary messages like protobufs.
MessageText is for UTF-8 encoded text messages like JSON.
StatusAbnormalClosure is exported for use only with Wasm.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
StatusNoStatusRcvd cannot be sent in a close message.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
StatusTLSHandshake is only exported for use with Wasm.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.
https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number These are only the status codes defined by the protocol.

# Structs

AcceptOptions represents Accept's options.
CloseError is returned when the connection is closed with a status and reason.
Conn represents a WebSocket connection.
DialOptions represents Dial's options.

# Type aliases

CompressionMode represents the modes available to the permessage-deflate extension.
MessageType represents the type of a WebSocket message.
StatusCode represents a WebSocket status code.