{"modulePath":"github.com/coder/websocket","version":"v1.8.15","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package websocket\n\nPackage websocket implements the RFC 6455 WebSocket protocol.\n\n[https://tools.ietf.org/html/rfc6455](https://tools.ietf.org/html/rfc6455)\n\nUse Dial to dial a WebSocket server.\n\nUse Accept to accept a WebSocket client.\n\nConn represents the resulting WebSocket connection.\n\nThe examples are the best way to understand how to correctly use the library.\n\nThe wsjson subpackage contain helpers for JSON and protobuf messages.\n\nMore documentation at [https://github.com/coder/websocket](https://github.com/coder/websocket).\n\n### Wasm {#hdr-Wasm}\n\nThe client side supports compiling to Wasm. It wraps the WebSocket browser API.\n\nSee [https://developer.mozilla.org/en-US/docs/Web/API/WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)\n\nSome important caveats to be aware of:\n\n  - Accept always errors out\n  - Conn.Ping is no-op\n  - Conn.CloseNow is Close(StatusGoingAway, \"\")\n  - HTTPClient, HTTPHeader and CompressionMode in DialOptions are no-op\n  - \\*http.Response from Dial is \u0026http.Response{} with a 101 status code on success\n\n## Variables\n\n```go\nvar ErrMessageTooBig = errors.New(\"websocket: message too big\")\n```\nErrMessageTooBig is returned when a message exceeds the read limit.\n\n## Functions\n\n```go\nfunc NetConn(ctx context.Context, c *Conn, msgType MessageType) net.Conn\n```\nNetConn converts a \\*websocket.Conn into a net.Conn.\n\nIt'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](https://github.com/nhooyr/websocket/issues/100).\n\nEvery Write to the net.Conn will correspond to a message write of the given type on \\*websocket.Conn.\n\nThe passed ctx bounds the lifetime of the net.Conn. If cancelled, all reads and writes on the net.Conn will be cancelled.\n\nIf a message is read that is not of the correct type, the connection will be closed with StatusUnsupportedData and an error will be returned.\n\nClose will close the \\*websocket.Conn with StatusNormalClosure.\n\nWhen a deadline is hit and there is an active read or write goroutine, 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.\n\nThe Addr methods will return the real addresses for connections obtained from websocket.Accept. But for connections obtained from websocket.Dial, a mock net.Addr will be returned that gives \"websocket\" for Network() and \"websocket/unknown-addr\" for String(). This is because websocket.Dial only exposes a io.ReadWriteCloser instead of the full net.Conn to us.\n\nWhen running as WASM, the Addr methods will always return the mock address described above.\n\nA received StatusNormalClosure or StatusGoingAway close frame will be translated to io.EOF when reading.\n\nFurthermore, the ReadLimit is set to -1 to disable it.\n\n## Types\n\n```go\ntype AcceptOptions struct {\n\t// Subprotocols lists the WebSocket subprotocols that Accept will negotiate with the client.\n\t// The empty subprotocol will always be negotiated as per RFC 6455. If you would like to\n\t// reject it, close the connection when c.Subprotocol() == \"\".\n\tSubprotocols []string\n\n\t// InsecureSkipVerify is used to disable Accept's origin verification behaviour.\n\t//\n\t// You probably want to use OriginPatterns instead.\n\tInsecureSkipVerify bool\n\n\t// OriginPatterns lists the host patterns for authorized origins.\n\t// The request host is always authorized.\n\t// Use this to enable cross origin WebSockets.\n\t//\n\t// i.e javascript running on example.com wants to access a WebSocket server at chat.example.com.\n\t// In such a case, example.com is the origin and chat.example.com is the request host.\n\t// One would set this field to []string{\"example.com\"} to authorize example.com to connect.\n\t//\n\t// Each pattern is matched case insensitively with path.Match (see\n\t// https://golang.org/pkg/path/#Match). By default, it is matched\n\t// against the request origin host. If the pattern contains a URI\n\t// scheme (\"://\"), it will be matched against \"scheme://host\".\n\t//\n\t// Please ensure you understand the ramifications of enabling this.\n\t// If used incorrectly your WebSocket server will be open to CSRF attacks.\n\t//\n\t// Do not use * as a pattern to allow any origin, prefer to use InsecureSkipVerify instead\n\t// to bring attention to the danger of such a setting.\n\tOriginPatterns []string\n\n\t// CompressionMode controls the compression mode.\n\t// Defaults to CompressionDisabled.\n\t//\n\t// See docs on CompressionMode for details.\n\tCompressionMode CompressionMode\n\n\t// CompressionThreshold controls the minimum size of a message before compression is applied.\n\t//\n\t// Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes\n\t// for CompressionContextTakeover.\n\tCompressionThreshold int\n\n\t// OnPingReceived is an optional callback invoked synchronously when a ping frame is received.\n\t//\n\t// The payload contains the application data of the ping frame.\n\t// If the callback returns false, the subsequent pong frame will not be sent.\n\t// To avoid blocking, any expensive processing should be performed asynchronously using a goroutine.\n\tOnPingReceived func(ctx context.Context, payload []byte) bool\n\n\t// OnPongReceived is an optional callback invoked synchronously when a pong frame is received.\n\t//\n\t// The payload contains the application data of the pong frame.\n\t// To avoid blocking, any expensive processing should be performed asynchronously using a goroutine.\n\t//\n\t// Unlike OnPingReceived, this callback does not return a value because a pong frame\n\t// is a response to a ping and does not trigger any further frame transmission.\n\tOnPongReceived func(ctx context.Context, payload []byte)\n}\n```\nAcceptOptions represents Accept's options.\n\n```go\ntype CloseError struct {\n\tCode   StatusCode\n\tReason string\n}\n```\nCloseError is returned when the connection is closed with a status and reason.\n\nUse Go 1.13's errors.As to check for this error. Also see the CloseStatus helper.\n\n```go\nfunc (ce CloseError) Error() string\n```\n\n```go\ntype CompressionMode int\n```\nCompressionMode represents the modes available to the permessage-deflate extension. See [https://tools.ietf.org/html/rfc7692](https://tools.ietf.org/html/rfc7692)\n\nWorks in all modern browsers except Safari which does not implement the permessage-deflate extension.\n\nCompression is only used if the peer supports the mode selected.\n\n```go\nconst (\n\t// CompressionDisabled disables the negotiation of the permessage-deflate extension.\n\t//\n\t// This is the default. Do not enable compression without benchmarking for your particular use case first.\n\tCompressionDisabled CompressionMode = iota\n\n\t// CompressionContextTakeover compresses each message greater than 128 bytes reusing the 32 KB sliding window from\n\t// previous messages. i.e compression context across messages is preserved.\n\t//\n\t// As most WebSocket protocols are text based and repetitive, this compression mode can be very efficient.\n\t//\n\t// The memory overhead is a fixed 32 KB sliding window, a fixed 1.2 MB flate.Writer and a sync.Pool of 40 KB flate.Reader's\n\t// that are used when reading and then returned.\n\t//\n\t// Thus, it uses more memory than CompressionNoContextTakeover but compresses more efficiently.\n\t//\n\t// If the peer does not support CompressionContextTakeover then we will fall back to CompressionNoContextTakeover.\n\tCompressionContextTakeover\n\n\t// CompressionNoContextTakeover compresses each message greater than 512 bytes. Each message is compressed with\n\t// a new 1.2 MB flate.Writer pulled from a sync.Pool. Each message is read with a 40 KB flate.Reader pulled from\n\t// a sync.Pool.\n\t//\n\t// This means less efficient compression as the sliding window from previous messages will not be used but the\n\t// memory overhead will be lower as there will be no fixed cost for the flate.Writer nor the 32 KB sliding window.\n\t// Especially if the connections are long lived and seldom written to.\n\t//\n\t// Thus, it uses less memory than CompressionContextTakeover but compresses less efficiently.\n\t//\n\t// If the peer does not support CompressionNoContextTakeover then we will fall back to CompressionDisabled.\n\tCompressionNoContextTakeover\n)\n```\n\n```go\ntype Conn struct {\n\t// contains filtered or unexported fields\n}\n```\nConn represents a WebSocket connection. All methods may be called concurrently except for Reader and Read.\n\nYou must always read from the connection. Otherwise control frames will not be handled. See Reader and CloseRead.\n\nBe sure to call Close on the connection when you are finished with it to release associated resources.\n\nOn any error from any method, the connection is closed with an appropriate reason.\n\nThis applies to context expirations as well unfortunately. See [https://github.com/nhooyr/websocket/issues/242#issuecomment-633182220](https://github.com/nhooyr/websocket/issues/242#issuecomment-633182220)\n\n```go\nfunc Accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (*Conn, error)\n```\nAccept accepts a WebSocket handshake from a client and upgrades the connection to a WebSocket.\n\nAccept will not allow cross origin requests by default. See the InsecureSkipVerify and OriginPatterns options to allow cross origin requests.\n\nAccept will write a response to w on all errors.\n\nNote that using the http.Request Context after Accept returns may lead to unexpected behavior (see http.Hijacker).\n\n```go\nfunc Dial(ctx context.Context, u string, opts *DialOptions) (*Conn, *http.Response, error)\n```\nDial performs a WebSocket handshake on url.\n\nThe response is the WebSocket handshake response from the server. You never need to close resp.Body yourself.\n\nIf an error occurs, the returned response may be non nil. However, you can only read the first 1024 bytes of the body.\n\nThis 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](https://github.com/golang/go/issues/26937#issuecomment-415855861)\n\nURLs with http/https schemes will work and are interpreted as ws/wss.\n\n```go\nfunc (c *Conn) Close(code StatusCode, reason string) (err error)\n```\nClose performs the WebSocket close handshake with the given status code and reason.\n\nIt 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.\n\nThe connection can only be closed once. Additional calls to Close are no-ops.\n\nThe maximum length of reason must be 125 bytes. Avoid sending a dynamic reason.\n\nClose will unblock all goroutines interacting with the connection once complete.\n\n```go\nfunc (c *Conn) CloseNow() (err error)\n```\nCloseNow closes the WebSocket connection without attempting a close handshake. Use when you do not want the overhead of the close handshake.\n\n```go\nfunc (c *Conn) CloseRead(ctx context.Context) context.Context\n```\nCloseRead starts a goroutine to read from the connection until it is closed or a data message is received.\n\nOnce CloseRead is called you cannot read any messages from the connection. The returned context will be cancelled when the connection is closed.\n\nIf a data message is received, the connection will be closed with StatusPolicyViolation.\n\nCall 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. This means c.Ping and c.Close will still work as expected.\n\nThis function is idempotent.\n\n```go\nfunc (c *Conn) Ping(ctx context.Context) error\n```\nPing 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.\n\nTCP Keepalives should suffice for most use cases.\n\n```go\nfunc (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)\n```\nRead is a convenience method around Reader to read a single message from the connection.\n\n```go\nfunc (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error)\n```\nReader reads from the connection until there is a WebSocket data message to be read. It will handle ping, pong and close frames as appropriate.\n\nIt 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.\n\nCall CloseRead if you do not expect any data messages from the peer.\n\nOnly one Reader may be open at a time.\n\nIf you need a separate timeout on the Reader call and the Read itself, use time.AfterFunc to cancel the context passed in. See [https://github.com/nhooyr/websocket/issues/87#issue-451703332](https://github.com/nhooyr/websocket/issues/87#issue-451703332) Most users should not need this.\n\n```go\nfunc (c *Conn) SetReadLimit(n int64)\n```\nSetReadLimit sets the max number of bytes to read for a single message. It applies to the Reader and Read methods.\n\nBy default, the connection has a message read limit of 32768 bytes.\n\nWhen the limit is hit, reads return an error wrapping ErrMessageTooBig and the connection is closed with StatusMessageTooBig.\n\nSet to -1 to disable.\n\n```go\nfunc (c *Conn) Subprotocol() string\n```\nSubprotocol returns the negotiated subprotocol. An empty string means the default protocol.\n\n```go\nfunc (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error\n```\nWrite writes a message to the connection.\n\nSee the Writer method if you want to stream a message.\n\nIf compression is disabled or the compression threshold is not met, then it will write the message in a single frame.\n\n```go\nfunc (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error)\n```\nWriter returns a writer bounded by the context that will write a WebSocket message of type dataType to the connection.\n\nYou must close the writer once you have written the entire message.\n\nOnly one writer can be open at a time, multiple calls will block until the previous writer is closed.\n\n```go\ntype DialOptions struct {\n\t// HTTPClient is used for the connection.\n\t// Its Transport must return writable bodies for WebSocket handshakes.\n\t// http.Transport does beginning with Go 1.12.\n\tHTTPClient *http.Client\n\n\t// HTTPHeader specifies the HTTP headers included in the handshake request.\n\tHTTPHeader http.Header\n\n\t// Host optionally overrides the Host HTTP header to send. If empty, the value\n\t// of URL.Host will be used.\n\tHost string\n\n\t// Subprotocols lists the WebSocket subprotocols to negotiate with the server.\n\tSubprotocols []string\n\n\t// CompressionMode controls the compression mode.\n\t// Defaults to CompressionDisabled.\n\t//\n\t// See docs on CompressionMode for details.\n\tCompressionMode CompressionMode\n\n\t// CompressionThreshold controls the minimum size of a message before compression is applied.\n\t//\n\t// Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes\n\t// for CompressionContextTakeover.\n\tCompressionThreshold int\n\n\t// OnPingReceived is an optional callback invoked synchronously when a ping frame is received.\n\t//\n\t// The payload contains the application data of the ping frame.\n\t// If the callback returns false, the subsequent pong frame will not be sent.\n\t// To avoid blocking, any expensive processing should be performed asynchronously using a goroutine.\n\tOnPingReceived func(ctx context.Context, payload []byte) bool\n\n\t// OnPongReceived is an optional callback invoked synchronously when a pong frame is received.\n\t//\n\t// The payload contains the application data of the pong frame.\n\t// To avoid blocking, any expensive processing should be performed asynchronously using a goroutine.\n\t//\n\t// Unlike OnPingReceived, this callback does not return a value because a pong frame\n\t// is a response to a ping and does not trigger any further frame transmission.\n\tOnPongReceived func(ctx context.Context, payload []byte)\n}\n```\nDialOptions represents Dial's options.\n\n```go\ntype MessageType int\n```\nMessageType represents the type of a WebSocket message. See [https://tools.ietf.org/html/rfc6455#section-5.6](https://tools.ietf.org/html/rfc6455#section-5.6)\n\n```go\nconst (\n\t// MessageText is for UTF-8 encoded text messages like JSON.\n\tMessageText MessageType = iota + 1\n\t// MessageBinary is for binary messages like protobufs.\n\tMessageBinary\n)\n```\nMessageType constants.\n\n```go\nfunc (i MessageType) String() string\n```\n\n```go\ntype StatusCode int\n```\nStatusCode represents a WebSocket status code. [https://tools.ietf.org/html/rfc6455#section-7.4](https://tools.ietf.org/html/rfc6455#section-7.4)\n\n```go\nconst (\n\tStatusNormalClosure   StatusCode = 1000\n\tStatusGoingAway       StatusCode = 1001\n\tStatusProtocolError   StatusCode = 1002\n\tStatusUnsupportedData StatusCode = 1003\n\n\t// StatusNoStatusRcvd cannot be sent in a close message.\n\t// It is reserved for when a close message is received without\n\t// a status code.\n\tStatusNoStatusRcvd StatusCode = 1005\n\n\t// StatusAbnormalClosure is exported for use only with Wasm.\n\t// In non Wasm Go, the returned error will indicate whether the\n\t// connection was closed abnormally.\n\tStatusAbnormalClosure StatusCode = 1006\n\n\tStatusInvalidFramePayloadData StatusCode = 1007\n\tStatusPolicyViolation         StatusCode = 1008\n\tStatusMessageTooBig           StatusCode = 1009\n\tStatusMandatoryExtension      StatusCode = 1010\n\tStatusInternalError           StatusCode = 1011\n\tStatusServiceRestart          StatusCode = 1012\n\tStatusTryAgainLater           StatusCode = 1013\n\tStatusBadGateway              StatusCode = 1014\n\n\t// StatusTLSHandshake is only exported for use with Wasm.\n\t// In non Wasm Go, the returned error will indicate whether there was\n\t// a TLS handshake failure.\n\tStatusTLSHandshake StatusCode = 1015\n)\n```\n[https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number](https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number)\n\nThese are only the status codes defined by the protocol.\n\nYou 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.\n\n```go\nfunc CloseStatus(err error) StatusCode\n```\nCloseStatus is a convenience wrapper around Go 1.13's errors.As to grab the status code from a CloseError.\n\n\\-1 will be returned if the passed error is nil or not a CloseError.\n\n```go\nfunc (i StatusCode) String() string\n```\n\n","path":"github.com/coder/websocket","name":"websocket","synopsis":"Package websocket implements the RFC 6455 WebSocket protocol.","isRedistributable":true}
