A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://pkg.go.dev/github.com/gorilla/websocket below:

websocket package - github.com/gorilla/websocket - Go Packages

Package websocket implements the WebSocket protocol defined in RFC 6455.

Overview

The Conn type represents a WebSocket connection. A server application calls the Upgrader.Upgrade method from an HTTP request handler to get a *Conn:

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func handler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }
    ... Use conn to send and receive messages.
}

Call the connection's WriteMessage and ReadMessage methods to send and receive messages as a slice of bytes. This snippet of code shows how to echo messages using these methods:

for {
    messageType, p, err := conn.ReadMessage()
    if err != nil {
        log.Println(err)
        return
    }
    if err := conn.WriteMessage(messageType, p); err != nil {
        log.Println(err)
        return
    }
}

In above snippet of code, p is a []byte and messageType is an int with value websocket.BinaryMessage or websocket.TextMessage.

An application can also send and receive messages using the io.WriteCloser and io.Reader interfaces. To send a message, call the connection NextWriter method to get an io.WriteCloser, write the message to the writer and close the writer when done. To receive a message, call the connection NextReader method to get an io.Reader and read until io.EOF is returned. This snippet shows how to echo messages using the NextWriter and NextReader methods:

for {
    messageType, r, err := conn.NextReader()
    if err != nil {
        return
    }
    w, err := conn.NextWriter(messageType)
    if err != nil {
        return err
    }
    if _, err := io.Copy(w, r); err != nil {
        return err
    }
    if err := w.Close(); err != nil {
        return err
    }
}
Data Messages

The WebSocket protocol distinguishes between text and binary data messages. Text messages are interpreted as UTF-8 encoded text. The interpretation of binary messages is left to the application.

This package uses the TextMessage and BinaryMessage integer constants to identify the two data message types. The ReadMessage and NextReader methods return the type of the received message. The messageType argument to the WriteMessage and NextWriter methods specifies the type of a sent message.

It is the application's responsibility to ensure that text messages are valid UTF-8 encoded text.

Control Messages

The WebSocket protocol defines three types of control messages: close, ping and pong. Call the connection WriteControl, WriteMessage or NextWriter methods to send a control message to the peer.

Connections handle received close messages by calling the handler function set with the SetCloseHandler method and by returning a *CloseError from the NextReader, ReadMessage or the message Read method. The default close handler sends a close message to the peer.

Connections handle received ping messages by calling the handler function set with the SetPingHandler method. The default ping handler sends a pong message to the peer.

Connections handle received pong messages by calling the handler function set with the SetPongHandler method. The default pong handler does nothing. If an application sends ping messages, then the application should set a pong handler to receive the corresponding pong.

The control message handler functions are called from the NextReader, ReadMessage and message reader Read methods. The default close and ping handlers can block these methods for a short time when the handler writes to the connection.

The application must read the connection to process close, ping and pong messages sent from the peer. If the application is not otherwise interested in messages from the peer, then the application should start a goroutine to read and discard messages from the peer. A simple example is:

func readLoop(c *websocket.Conn) {
    for {
        if _, _, err := c.NextReader(); err != nil {
            c.Close()
            break
        }
    }
}
Concurrency

Connections support one concurrent reader and one concurrent writer.

Applications are responsible for ensuring that no more than one goroutine calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and that no more than one goroutine calls the read methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) concurrently.

The Close and WriteControl methods can be called concurrently with all other methods.

Origin Considerations

Web browsers allow Javascript applications to open a WebSocket connection to any host. It's up to the server to enforce an origin policy using the Origin request header sent by the browser.

The Upgrader calls the function specified in the CheckOrigin field to check the origin. If the CheckOrigin function returns false, then the Upgrade method fails the WebSocket handshake with HTTP status 403.

If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail the handshake if the Origin request header is present and the Origin host is not equal to the Host request header.

The deprecated package-level Upgrade function does not perform origin checking. The application is responsible for checking the Origin header before calling the Upgrade function.

Buffers

Connections buffer network input and output to reduce the number of system calls when reading or writing messages.

Write buffers are also used for constructing WebSocket frames. See RFC 6455, Section 5 for a discussion of message framing. A WebSocket frame header is written to the network each time a write buffer is flushed to the network. Decreasing the size of the write buffer can increase the amount of framing overhead on the connection.

The buffer sizes in bytes are specified by the ReadBufferSize and WriteBufferSize fields in the Dialer and Upgrader. The Dialer uses a default size of 4096 when a buffer size field is set to zero. The Upgrader reuses buffers created by the HTTP server when a buffer size field is set to zero. The HTTP server buffers have a size of 4096 at the time of this writing.

The buffer sizes do not limit the size of a message that can be read or written by a connection.

Buffers are held for the lifetime of the connection by default. If the Dialer or Upgrader WriteBufferPool field is set, then a connection holds the write buffer only when writing a message.

Applications should tune the buffer sizes to balance memory use and performance. Increasing the buffer size uses more memory, but can reduce the number of system calls to read or write the network. In the case of writing, increasing the buffer size can reduce the number of frame headers written to the network.

Some guidelines for setting buffer parameters are:

Limit the buffer sizes to the maximum expected message size. Buffers larger than the largest message do not provide any benefit.

Depending on the distribution of message sizes, setting the buffer size to a value less than the maximum expected message size can greatly reduce memory use with a small impact on performance. Here's an example: If 99% of the messages are smaller than 256 bytes and the maximum message size is 512 bytes, then a buffer size of 256 bytes will result in 1.01 more system calls than a buffer size of 512 bytes. The memory savings is 50%.

A write buffer pool is useful when the application has a modest number writes over a large number of connections. when buffers are pooled, a larger buffer size has a reduced impact on total memory use and has the benefit of reducing system calls and frame overhead.

Compression EXPERIMENTAL

Per message compression extensions (RFC 7692) are experimentally supported by this package in a limited capacity. Setting the EnableCompression option to true in Dialer or Upgrader will attempt to negotiate per message deflate support.

var upgrader = websocket.Upgrader{
    EnableCompression: true,
}

If compression was successfully negotiated with the connection's peer, any message received in compressed form will be automatically decompressed. All Read methods will return uncompressed bytes.

Per message compression of messages written to a connection can be enabled or disabled by calling the corresponding Conn method:

conn.EnableWriteCompression(false)

Currently this package does not support compression with "context takeover". This means that messages must be compressed and decompressed in isolation, without retaining sliding window or dictionary state across messages. For more details refer to RFC 7692.

Use of compression is experimental and may result in decreased performance.

View Source
const (
	CloseNormalClosure           = 1000
	CloseGoingAway               = 1001
	CloseProtocolError           = 1002
	CloseUnsupportedData         = 1003
	CloseNoStatusReceived        = 1005
	CloseAbnormalClosure         = 1006
	CloseInvalidFramePayloadData = 1007
	ClosePolicyViolation         = 1008
	CloseMessageTooBig           = 1009
	CloseMandatoryExtension      = 1010
	CloseInternalServerErr       = 1011
	CloseServiceRestart          = 1012
	CloseTryAgainLater           = 1013
	CloseTLSHandshake            = 1015
)

Close codes defined in RFC 6455, section 11.7.

View Source
const (
	
	
	TextMessage = 1

	
	BinaryMessage = 2

	
	
	
	CloseMessage = 8

	
	
	PingMessage = 9

	
	
	PongMessage = 10
)

The message types are defined in RFC 6455, section 11.8.

DefaultDialer is a dialer with all fields set to the default values.

ErrBadHandshake is returned when the server response to opening handshake is invalid.

ErrCloseSent is returned when the application writes a message to the connection after sending a close message.

ErrReadLimit is returned when reading a message that is larger than the read limit set for the connection.

FormatCloseMessage formats closeCode and text as a WebSocket close message. An empty message is returned for code CloseNoStatusReceived.

IsCloseError returns boolean indicating whether the error is a *CloseError with one of the specified codes.

func IsUnexpectedCloseError(err error, expectedCodes ...int) bool

IsUnexpectedCloseError returns boolean indicating whether the error is a *CloseError with a code not in the list of expected codes.

The websocket.IsUnexpectedCloseError function is useful for identifying application and protocol errors.

This server application works with a client application running in the browser. The client application does not explicitly close the websocket. The only expected close message from the client has the code websocket.CloseGoingAway. All other close messages are likely the result of an application or protocol error and are logged to aid debugging.

package main

import (
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var (
	c   *websocket.Conn
	req *http.Request
)

func main() {
	for {
		messageType, p, err := c.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v, user-agent: %v", err, req.Header.Get("User-Agent"))
			}
			return
		}
		processMessage(messageType, p)
	}
}

func processMessage(mt int, p []byte) {}

IsWebSocketUpgrade returns true if the client requested upgrade to the WebSocket protocol.

JoinMessages concatenates received messages to create a single io.Reader. The string term is appended to each message. The returned reader does not support concurrent calls to the Read method.

ReadJSON reads the next JSON-encoded message from the connection and stores it in the value pointed to by v.

Deprecated: Use c.ReadJSON instead.

Subprotocols returns the subprotocols requested by the client in the Sec-Websocket-Protocol header.

WriteJSON writes the JSON encoding of v as a message.

Deprecated: Use c.WriteJSON instead.

type BufferPool interface {
	
	Get() interface{}
	
	Put(interface{})
}

BufferPool represents a pool of buffers. The *sync.Pool type satisfies this interface. The type of the value stored in a pool is not specified.

type CloseError struct {
	
	Code int

	
	Text string
}

CloseError represents a close message.

The Conn type represents a WebSocket connection.

NewClient creates a new client connection using the given net connection. The URL u specifies the host and request URI. Use requestHeader to specify the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). Use the response.Header to get the selected subprotocol (Sec-WebSocket-Protocol) and cookies (Set-Cookie).

If the WebSocket handshake fails, ErrBadHandshake is returned along with a non-nil *http.Response so that callers can handle redirects, authentication, etc.

Deprecated: Use Dialer instead.

Upgrade upgrades the HTTP server connection to the WebSocket protocol.

Deprecated: Use websocket.Upgrader instead.

Upgrade does not perform origin checking. The application is responsible for checking the Origin header before calling Upgrade. An example implementation of the same origin policy check is:

if req.Header.Get("Origin") != "http://"+req.Host {
	http.Error(w, "Origin not allowed", http.StatusForbidden)
	return
}

If the endpoint supports subprotocols, then the application is responsible for negotiating the protocol used on the connection. Use the Subprotocols() function to get the subprotocols requested by the client. Use the Sec-Websocket-Protocol response header to specify the subprotocol selected by the application.

The responseHeader is included in the response to the client's upgrade request. Use the responseHeader to specify cookies (Set-Cookie) and the negotiated subprotocol (Sec-Websocket-Protocol).

The connection buffers IO to the underlying network connection. The readBufSize and writeBufSize parameters specify the size of the buffers to use. Messages can be larger than the buffers.

If the request is not a valid WebSocket handshake, then Upgrade returns an error of type HandshakeError. Applications should handle this error by replying to the client with an HTTP error response.

Close closes the underlying network connection without sending or waiting for a close message.

func (*Conn) CloseHandler added in v1.1.0

CloseHandler returns the current close handler

func (c *Conn) EnableWriteCompression(enable bool)

EnableWriteCompression enables and disables write compression of subsequent text and binary messages. This function is a noop if compression was not negotiated with the peer.

LocalAddr returns the local network address.

NetConn returns the underlying connection that is wrapped by c. Note that writing to or reading from this connection directly will corrupt the WebSocket connection.

NextReader returns the next data message received from the peer. The returned messageType is either TextMessage or BinaryMessage.

There can be at most one open reader on a connection. NextReader discards the previous message if the application has not already consumed it.

Applications must break out of the application's read loop when this method returns a non-nil error value. Errors returned from this method are permanent. Once this method returns a non-nil error, all subsequent calls to this method return the same error.

NextWriter returns a writer for the next message to send. The writer's Close method flushes the complete message to the network.

There can be at most one open writer on a connection. NextWriter closes the previous writer if the application has not already done so.

All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and PongMessage) are supported.

func (*Conn) PingHandler added in v1.1.0

PingHandler returns the current ping handler

func (*Conn) PongHandler added in v1.1.0

PongHandler returns the current pong handler

ReadJSON reads the next JSON-encoded message from the connection and stores it in the value pointed to by v.

See the documentation for the encoding/json Unmarshal function for details about the conversion of JSON to a Go value.

ReadMessage is a helper method for getting a reader using NextReader and reading from that reader to a buffer.

RemoteAddr returns the remote network address.

func (*Conn) SetCloseHandler added in v1.1.0

SetCloseHandler sets the handler for close messages received from the peer. The code argument to h is the received close code or CloseNoStatusReceived if the close message is empty. The default close handler sends a close message back to the peer.

The handler function is called from the NextReader, ReadMessage and message reader Read methods. The application must read the connection to process close messages as described in the section on Control Messages above.

The connection read methods return a CloseError when a close message is received. Most applications should handle close messages as part of their normal error handling. Applications should only set a close handler when the application must perform some action before sending a close message back to the peer.

SetCompressionLevel sets the flate compression level for subsequent text and binary messages. This function is a noop if compression was not negotiated with the peer. See the compress/flate package for a description of compression levels.

func (*Conn) SetPingHandler

SetPingHandler sets the handler for ping messages received from the peer. The appData argument to h is the PING message application data. The default ping handler sends a pong to the peer.

The handler function is called from the NextReader, ReadMessage and message reader Read methods. The application must read the connection to process ping messages as described in the section on Control Messages above.

func (*Conn) SetPongHandler

SetPongHandler sets the handler for pong messages received from the peer. The appData argument to h is the PONG message application data. The default pong handler does nothing.

The handler function is called from the NextReader, ReadMessage and message reader Read methods. The application must read the connection to process pong messages as described in the section on Control Messages above.

SetReadDeadline sets the read deadline on the underlying network connection. After a read has timed out, the websocket connection state is corrupt and all future reads will return an error. A zero value for t means reads will not time out.

SetReadLimit sets the maximum size in bytes for a message read from the peer. If a message exceeds the limit, the connection sends a close message to the peer and returns ErrReadLimit to the application.

SetWriteDeadline sets the write deadline on the underlying network connection. After a write has timed out, the websocket state is corrupt and all future writes will return an error. A zero value for t means writes will not time out.

Subprotocol returns the negotiated protocol for the connection.

UnderlyingConn returns the internal net.Conn. This can be used to further modifications to connection specific flags. Deprecated: Use the NetConn method.

WriteControl writes a control message with the given deadline. The allowed message types are CloseMessage, PingMessage and PongMessage.

func (c *Conn) WriteJSON(v interface{}) error

WriteJSON writes the JSON encoding of v as a message.

See the documentation for encoding/json Marshal for details about the conversion of Go values to JSON.

WriteMessage is a helper method for getting a writer using NextWriter, writing the message and closing the writer.

WritePreparedMessage writes prepared message into connection.

type Dialer struct {
	
	
	NetDial func(network, addr string) (net.Conn, error)

	
	
	NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)

	
	
	
	
	NetDialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)

	
	
	
	
	Proxy func(*http.Request) (*url.URL, error)

	
	
	
	
	TLSClientConfig *tls.Config

	
	HandshakeTimeout time.Duration

	
	
	
	ReadBufferSize, WriteBufferSize int

	
	
	
	
	
	
	
	
	
	WriteBufferPool BufferPool

	
	Subprotocols []string

	
	
	
	
	EnableCompression bool

	
	
	
	Jar http.CookieJar
}

A Dialer contains options for connecting to WebSocket server.

It is safe to call Dialer's methods concurrently.

Dial creates a new client connection by calling DialContext with a background context.

DialContext creates a new client connection. Use requestHeader to specify the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). Use the response.Header to get the selected subprotocol (Sec-WebSocket-Protocol) and cookies (Set-Cookie).

The context will be used in the request and in the Dialer.

If the WebSocket handshake fails, ErrBadHandshake is returned along with a non-nil *http.Response so that callers can handle redirects, authentication, etcetera. The response body may not contain the entire response and does not need to be closed by the application.

type HandshakeError
type HandshakeError struct {
	
}

HandshakeError describes an error with the handshake from the peer.

type PreparedMessage struct {
	
}

PreparedMessage caches on the wire representations of a message payload. Use PreparedMessage to efficiently send a message payload to multiple connections. PreparedMessage is especially useful when compression is used because the CPU and memory expensive compression operation can be executed once for a given set of compression options.

NewPreparedMessage returns an initialized PreparedMessage. You can then send it to connection using WritePreparedMessage method. Valid wire representation will be calculated lazily only once for a set of current connection options.

Upgrader specifies parameters for upgrading an HTTP connection to a WebSocket connection.

It is safe to call Upgrader's methods concurrently.

Upgrade upgrades the HTTP server connection to the WebSocket protocol.

The responseHeader is included in the response to the client's upgrade request. Use the responseHeader to specify cookies (Set-Cookie). To specify subprotocols supported by the server, set Upgrader.Subprotocols directly.

If the upgrade fails, then Upgrade replies to the client with an HTTP error response.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4