websocket

package module
v1.8.5-0...-8b8590f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 3, 2020 License: MIT Imports: 27 Imported by: 0

README

websocket

godoc

websocket is a minimal and idiomatic WebSocket library for Go.

Install

go get github.com/matthewpi/websocket

Features

Roadmap

  • HTTP/2 #4

Examples

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

For a full stack example, see ./chat-example.

Server
http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	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", nil)
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, "")

Comparison

gorilla/websocket

Advantages of gorilla/websocket:

Advantages of github.com/matthewpi/websocket:

golang.org/x/net/websocket

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

The net.Conn wrapper will ease in transitioning to github.com/matthewpi/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 when writing idiomatic Go, github.com/matthewpi/websocket will be faster and easier to use.

Documentation

Overview

Package websocket implements the RFC 6455 WebSocket protocol.

https://tools.ietf.org/html/rfc6455

Use Dial to dial a WebSocket server.

Use Accept to accept a WebSocket client.

Conn represents the resulting WebSocket connection.

The examples are the best way to understand how to correctly use the library.

The wsjson and wspb subpackages contain helpers for JSON and protobuf messages.

More documentation at https://github.com/matthewpi/websocket.

Wasm

The client side supports compiling to Wasm. It wraps the WebSocket browser API.

See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

Some important caveats to be aware of:

  • Accept always errors out
  • Conn.Ping is no-op
  • HTTPClient, HTTPHeader and CompressionMode in DialOptions are no-op
  • *http.Response from Dial is &http.Response{} with a 101 status code on success
Example (Echo)

This example starts a WebSocket echo server, dials the server and then sends 5 different messages and prints out the server's responses.

//go:build !js
// +build !js

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"time"

	"golang.org/x/time/rate"

	"github.com/matthewpi/websocket"
	"github.com/matthewpi/websocket/wsjson"
)

// This example starts a WebSocket echo server,
// dials the server and then sends 5 different messages
// and prints out the server's responses.
func main() {
	// First we listen on port 0 which means the OS will
	// assign us a random free port. This is the listener
	// the server will serve on and the client will connect to.
	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	defer l.Close()

	s := &http.Server{
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			err := echoServer(w, r)
			if err != nil {
				log.Printf("echo server: %v", err)
			}
		}),
		ReadTimeout:  time.Second * 15,
		WriteTimeout: time.Second * 15,
	}
	defer s.Close()

	// This starts the echo server on the listener.
	go func() {
		err := s.Serve(l)
		if err != http.ErrServerClosed {
			log.Fatalf("failed to listen and serve: %v", err)
		}
	}()

	// Now we dial the server, send the messages and echo the responses.
	err = client("ws://" + l.Addr().String())
	if err != nil {
		log.Fatalf("client failed: %v", err)
	}
}

// echoServer is the WebSocket echo server implementation.
// It ensures the client speaks the echo subprotocol and
// only allows one message every 100ms with a 10 message burst.
func echoServer(w http.ResponseWriter, r *http.Request) error {
	c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
		Subprotocols: []string{"echo"},
	})
	if err != nil {
		return err
	}
	defer c.Close(websocket.StatusInternalError, "the sky is falling")

	if c.Subprotocol() != "echo" {
		c.Close(websocket.StatusPolicyViolation, "client must speak the echo subprotocol")
		return errors.New("client does not speak echo sub protocol")
	}

	l := rate.NewLimiter(rate.Every(time.Millisecond*100), 10)
	for {
		err = echo(r.Context(), c, l)
		if websocket.CloseStatus(err) == websocket.StatusNormalClosure {
			return nil
		}
		if err != nil {
			return fmt.Errorf("failed to echo with %v: %w", r.RemoteAddr, err)
		}
	}
}

// echo reads from the WebSocket connection and then writes
// the received message back to it.
// The entire function has 10s to complete.
func echo(ctx context.Context, c *websocket.Conn, l *rate.Limiter) error {
	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	err := l.Wait(ctx)
	if err != nil {
		return err
	}

	typ, r, err := c.Reader(ctx)
	if err != nil {
		return err
	}

	w, err := c.Writer(ctx, typ)
	if err != nil {
		return err
	}

	_, err = io.Copy(w, r)
	if err != nil {
		return fmt.Errorf("failed to io.Copy: %w", err)
	}

	err = w.Close()
	return err
}

// client dials the WebSocket echo server at the given url.
// It then sends it 5 different messages and echo's the server's
// response to each.
func client(url string) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, url, &websocket.DialOptions{
		Subprotocols: []string{"echo"},
	})
	if err != nil {
		return err
	}
	defer c.Close(websocket.StatusInternalError, "the sky is falling")

	for i := 0; i < 5; i++ {
		err = wsjson.Write(ctx, c, map[string]int{
			"i": i,
		})
		if err != nil {
			return err
		}

		v := map[string]int{}
		err = wsjson.Read(ctx, c, &v)
		if err != nil {
			return err
		}

		fmt.Printf("received: %v\n", v)
	}

	c.Close(websocket.StatusNormalClosure, "")
	return nil
}
Output:

received: map[i:0]
received: map[i:1]
received: map[i:2]
received: map[i:3]
received: map[i:4]
Example (WriteOnly)

This example shows how to correctly handle a WebSocket connection on which you will only write and do not expect to read data messages.

package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/matthewpi/websocket"
	"github.com/matthewpi/websocket/wsjson"
)

func main() {
	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		defer c.Close(websocket.StatusInternalError, "the sky is falling")

		ctx, cancel := context.WithTimeout(r.Context(), time.Minute*10)
		defer cancel()

		ctx = c.CloseRead(ctx)

		t := time.NewTicker(time.Second * 30)
		defer t.Stop()

		for {
			select {
			case <-ctx.Done():
				c.Close(websocket.StatusNormalClosure, "")
				return
			case <-t.C:
				err = wsjson.Write(ctx, c, "hi")
				if err != nil {
					log.Println(err)
					return
				}
			}
		}
	})

	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NetConn

func NetConn(ctx context.Context, c *Conn, msgType MessageType) net.Conn

NetConn converts a *websocket.Conn into a net.Conn.

It's for tunneling arbitrary protocols over WebSockets. Few users of the library will need this but it's tricky to implement correctly and so provided in the library. See https://github.com/nhooyr/websocket/issues/100.

Every Write to the net.Conn will correspond to a message write of the given type on *websocket.Conn.

The passed ctx bounds the lifetime of the net.Conn. If cancelled, all reads and writes on the net.Conn will be cancelled.

If a message is read that is not of the correct type, the connection will be closed with StatusUnsupportedData and an error will be returned.

Close will close the *websocket.Conn with StatusNormalClosure.

When a deadline is hit, the connection will be closed. This is different from most net.Conn implementations where only the reading/writing goroutines are interrupted but the connection is kept alive.

The Addr methods will return a mock net.Addr that returns "websocket" for Network and "websocket/unknown-addr" for String.

A received StatusNormalClosure or StatusGoingAway close frame will be translated to io.EOF when reading.

Types

type AcceptOptions

type AcceptOptions struct {
	// Subprotocols lists the WebSocket subprotocols that Accept will negotiate with the client.
	// The empty subprotocol will always be negotiated as per RFC 6455. If you would like to
	// reject it, close the connection when c.Subprotocol() == "".
	Subprotocols []string

	// InsecureSkipVerify disables Accept's origin verification behaviour. By default,
	// the connection will only be accepted if the request origin is equal to the request
	// host.
	//
	// This is only required if you want javascript served from a different domain
	// to access your WebSocket server.
	//
	// See https://stackoverflow.com/a/37837709/4283659
	//
	// Please ensure you understand the ramifications of enabling this.
	// If used incorrectly your WebSocket server will be open to CSRF attacks.
	InsecureSkipVerify bool

	// CompressionMode controls the compression mode.
	// Defaults to CompressionNoContextTakeover.
	//
	// See docs on CompressionMode for details.
	CompressionMode CompressionMode

	// CompressionThreshold controls the minimum size of a message before compression is applied.
	//
	// Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes
	// for CompressionContextTakeover.
	CompressionThreshold int
}

AcceptOptions represents Accept's options.

type CloseError

type CloseError struct {
	Code   StatusCode
	Reason string
}

CloseError is returned when the connection is closed with a status and reason.

Use Go 1.13's errors.As to check for this error. Also see the CloseStatus helper.

func (CloseError) Error

func (ce CloseError) Error() string

type CompressionMode

type CompressionMode int

CompressionMode represents the modes available to the deflate extension. See https://tools.ietf.org/html/rfc7692

A compatibility layer is implemented for the older deflate-frame extension used by safari. See https://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate-06 It will work the same in every way except that we cannot signal to the peer we want to use no context takeover on our side, we can only signal that they should.

const (
	// CompressionNoContextTakeover grabs a new flate.Reader and flate.Writer as needed
	// for every message. This applies to both server and client side.
	//
	// This means less efficient compression as the sliding window from previous messages
	// will not be used but the memory overhead will be lower if the connections
	// are long lived and seldom used.
	//
	// The message will only be compressed if greater than 512 bytes.
	CompressionNoContextTakeover CompressionMode = iota

	// CompressionContextTakeover uses a flate.Reader and flate.Writer per connection.
	// This enables reusing the sliding window from previous messages.
	// As most WebSocket protocols are repetitive, this can be very efficient.
	// It carries an overhead of 8 kB for every connection compared to CompressionNoContextTakeover.
	//
	// If the peer negotiates NoContextTakeover on the client or server side, it will be
	// used instead as this is required by the RFC.
	CompressionContextTakeover

	// CompressionDisabled disables the deflate extension.
	//
	// Use this if you are using a predominantly binary protocol with very
	// little duplication in between messages or CPU and memory are more
	// important than bandwidth.
	CompressionDisabled
)

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn represents a WebSocket connection. All methods may be called concurrently except for Reader and Read.

You must always read from the connection. Otherwise control frames will not be handled. See Reader and CloseRead.

Be sure to call Close on the connection when you are finished with it to release associated resources.

On any error from any method, the connection is closed with an appropriate reason.

func Accept

func Accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (*Conn, error)

Accept accepts a WebSocket handshake from a client and upgrades the the connection to a WebSocket.

Accept will not allow cross origin requests by default. See the InsecureSkipVerify option to allow cross origin requests.

Accept will write a response to w on all errors.

Example

This example accepts a WebSocket connection, reads a single JSON message from the client and then closes the connection.

package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/matthewpi/websocket"
	"github.com/matthewpi/websocket/wsjson"
)

func main() {
	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		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.Println(err)
			return
		}

		c.Close(websocket.StatusNormalClosure, "")
	})

	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
}
Output:

func Dial

func Dial(ctx context.Context, u string, opts *DialOptions) (*Conn, *http.Response, error)

Dial performs a WebSocket handshake on url.

The response is the WebSocket handshake response from the server. You never need to close resp.Body yourself.

If an error occurs, the returned response may be non nil. However, you can only read the first 1024 bytes of the body.

This function requires at least Go 1.12 as it uses a new feature in net/http to perform WebSocket handshakes. See docs on the HTTPClient option and https://github.com/golang/go/issues/26937#issuecomment-415855861

Example

This example dials a server, writes a single JSON message and then closes the connection.

package main

import (
	"context"
	"log"
	"time"

	"github.com/matthewpi/websocket"
	"github.com/matthewpi/websocket/wsjson"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close(websocket.StatusInternalError, "the sky is falling")

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

	c.Close(websocket.StatusNormalClosure, "")
}
Output:

func (*Conn) Close

func (c *Conn) Close(code StatusCode, reason string) error

Close performs the WebSocket close handshake with the given status code and reason.

It will write a WebSocket close frame with a timeout of 5s and then wait 5s for the peer to send a close frame. All data messages received from the peer during the close handshake will be discarded.

The connection can only be closed once. Additional calls to Close are no-ops.

The maximum length of reason must be 125 bytes. Avoid sending a dynamic reason.

Close will unblock all goroutines interacting with the connection once complete.

func (*Conn) CloseRead

func (c *Conn) CloseRead(ctx context.Context) context.Context

CloseRead starts a goroutine to read from the connection until it is closed or a data message is received.

Once CloseRead is called you cannot read any messages from the connection. The returned context will be cancelled when the connection is closed.

If a data message is received, the connection will be closed with StatusPolicyViolation.

Call CloseRead when you do not expect to read any more messages. Since it actively reads from the connection, it will ensure that ping, pong and close frames are responded to.

func (*Conn) Ping

func (c *Conn) Ping(ctx context.Context) error

Ping sends a ping to the peer and waits for a pong. Use this to measure latency or ensure the peer is responsive. Ping must be called concurrently with Reader as it does not read from the connection but instead waits for a Reader call to read the pong.

TCP Keepalives should suffice for most use cases.

func (*Conn) Read

func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)

Read is a convenience method around Reader to read a single message from the connection.

func (*Conn) Reader

func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error)

Reader reads from the connection until until there is a WebSocket data message to be read. It will handle ping, pong and close frames as appropriate.

It returns the type of the message and an io.Reader to read it. The passed context will also bound the reader. Ensure you read to EOF otherwise the connection will hang.

Call CloseRead if you do not expect any data messages from the peer.

Only one Reader may be open at a time.

func (*Conn) SetReadLimit

func (c *Conn) SetReadLimit(n int64)

SetReadLimit sets the max number of bytes to read for a single message. It applies to the Reader and Read methods.

By default, the connection has a message read limit of 32768 bytes.

When the limit is hit, the connection will be closed with StatusMessageTooBig.

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

Subprotocol returns the negotiated subprotocol. An empty string means the default protocol.

func (*Conn) Write

func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error

Write writes a message to the connection.

See the Writer method if you want to stream a message.

If compression is disabled or the threshold is not met, then it will write the message in a single frame.

func (*Conn) Writer

func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error)

Writer returns a writer bounded by the context that will write a WebSocket message of type dataType to the connection.

You must close the writer once you have written the entire message.

Only one writer can be open at a time, multiple calls will block until the previous writer is closed.

type DialOptions

type DialOptions struct {
	// HTTPClient is used for the connection.
	// Its Transport must return writable bodies for WebSocket handshakes.
	// http.Transport does beginning with Go 1.12.
	HTTPClient *http.Client

	// HTTPHeader specifies the HTTP headers included in the handshake request.
	HTTPHeader http.Header

	// Subprotocols lists the WebSocket subprotocols to negotiate with the server.
	Subprotocols []string

	// CompressionMode controls the compression mode.
	// Defaults to CompressionNoContextTakeover.
	//
	// See docs on CompressionMode for details.
	CompressionMode CompressionMode

	// CompressionThreshold controls the minimum size of a message before compression is applied.
	//
	// Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes
	// for CompressionContextTakeover.
	CompressionThreshold int
}

DialOptions represents Dial's options.

type MessageType

type MessageType int

MessageType represents the type of a WebSocket message. See https://tools.ietf.org/html/rfc6455#section-5.6

const (
	// MessageText is for UTF-8 encoded text messages like JSON.
	MessageText MessageType = iota + 1
	// MessageBinary is for binary messages like protobufs.
	MessageBinary
)

MessageType constants.

func (MessageType) String

func (i MessageType) String() string

type StatusCode

type StatusCode int

StatusCode represents a WebSocket status code. https://tools.ietf.org/html/rfc6455#section-7.4

const (
	StatusNormalClosure   StatusCode = 1000
	StatusGoingAway       StatusCode = 1001
	StatusProtocolError   StatusCode = 1002
	StatusUnsupportedData StatusCode = 1003

	// StatusNoStatusRcvd cannot be sent in a close message.
	// It is reserved for when a close message is received without
	// a status code.
	StatusNoStatusRcvd StatusCode = 1005

	// StatusAbnormalClosure is exported for use only with Wasm.
	// In non Wasm Go, the returned error will indicate whether the
	// connection was closed abnormally.
	StatusAbnormalClosure StatusCode = 1006

	StatusInvalidFramePayloadData StatusCode = 1007
	StatusPolicyViolation         StatusCode = 1008
	StatusMessageTooBig           StatusCode = 1009
	StatusMandatoryExtension      StatusCode = 1010
	StatusInternalError           StatusCode = 1011
	StatusServiceRestart          StatusCode = 1012
	StatusTryAgainLater           StatusCode = 1013
	StatusBadGateway              StatusCode = 1014

	// StatusTLSHandshake is only exported for use with Wasm.
	// In non Wasm Go, the returned error will indicate whether there was
	// a TLS handshake failure.
	StatusTLSHandshake StatusCode = 1015
)

https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number

These are only the status codes defined by the protocol.

You can define custom codes in the 3000-4999 range. The 3000-3999 range is reserved for use by libraries, frameworks and applications. The 4000-4999 range is reserved for private use.

func CloseStatus

func CloseStatus(err error) StatusCode

CloseStatus is a convenience wrapper around Go 1.13's errors.As to grab the status code from a CloseError.

-1 will be returned if the passed error is nil or not a CloseError.

Example

This example dials a server and then expects to be disconnected with status code websocket.StatusNormalClosure.

package main

import (
	"context"
	"log"
	"time"

	"github.com/matthewpi/websocket"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close(websocket.StatusInternalError, "the sky is falling")

	_, _, err = c.Reader(ctx)
	if websocket.CloseStatus(err) != websocket.StatusNormalClosure {
		log.Fatalf("expected to be disconnected with StatusNormalClosure but got: %v", err)
	}
}
Output:

func (StatusCode) String

func (i StatusCode) String() string

Directories

Path Synopsis
Package flate implements the DEFLATE compressed data format, described in RFC 1951.
Package flate implements the DEFLATE compressed data format, described in RFC 1951.
internal
test
Package test contains subpackages only used in tests.
Package test contains subpackages only used in tests.
wsjs
Package wsjs implements typed access to the browser javascript WebSocket API.
Package wsjs implements typed access to the browser javascript WebSocket API.
Package wsjson provides helpers for reading and writing JSON messages.
Package wsjson provides helpers for reading and writing JSON messages.
Package wspb provides helpers for reading and writing protobuf messages.
Package wspb provides helpers for reading and writing protobuf messages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL