Documentation ¶
Overview ¶
Package websocket implements the WebSocket protocol defined in RFC 6455.
Overview ¶
The Conn type represents a WebSocket connection. A server application uses the Upgrade function from an Upgrader object with a HTTP request handler to get a pointer to 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 WriteMessage and ReadMessages 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 { return } if err = conn.WriteMessage(messageType, p); err != nil { return err } }
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 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 ping and pong messages by invoking a callback function set with SetPingHandler and SetPongHandler methods. These callback functions can be invoked from the ReadMessage method, the NextReader method or from a call to the data message reader returned from NextReader.
Connections handle received close messages by returning an error from the ReadMessage method, the NextReader method or from a call to the data message reader returned from NextReader.
Concurrency ¶
A Conn supports a single concurrent caller to the write methods (NextWriter, SetWriteDeadline, WriteMessage) and a single concurrent caller to the read methods (NextReader, SetReadDeadline, ReadMessage). The Close and WriteControl methods can be called concurrently with all other methods.
Read is Required ¶
The application must read the connection to process ping and close 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 } } }
Index ¶
- Constants
- Variables
- func FormatCloseMessage(closeCode int, text string) []byte
- func ReadJSON(c *Conn, v interface{}) error
- func Subprotocols(r *http.Request) []string
- func WriteJSON(c *Conn, v interface{}) error
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) NextReader() (messageType int, r io.Reader, err error)
- func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error)
- func (c *Conn) ReadJSON(v interface{}) error
- func (c *Conn) ReadMessage() (messageType int, p []byte, err error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) SetPingHandler(h func(string) error)
- func (c *Conn) SetPongHandler(h func(string) error)
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetReadLimit(limit int64)
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) Subprotocol() string
- func (c *Conn) UnderlyingConn() net.Conn
- func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error
- func (c *Conn) WriteJSON(v interface{}) error
- func (c *Conn) WriteMessage(messageType int, data []byte) error
- type Dialer
- type HandshakeError
- type Upgrader
Constants ¶
const ( CloseNormalClosure = 1000 CloseGoingAway = 1001 CloseProtocolError = 1002 CloseUnsupportedData = 1003 CloseNoStatusReceived = 1005 CloseAbnormalClosure = 1006 CloseInvalidFramePayloadData = 1007 ClosePolicyViolation = 1008 CloseMessageTooBig = 1009 CloseMandatoryExtension = 1010 CloseInternalServerErr = 1011 CloseTLSHandshake = 1015 )
Close codes defined in RFC 6455, section 11.7.
const ( // TextMessage denotes a text data message. The text message payload is // interpreted as UTF-8 encoded text data. TextMessage = 1 // BinaryMessage denotes a binary data message. BinaryMessage = 2 // CloseMessage denotes a close control message. The optional message // payload contains a numeric code and text. Use the FormatCloseMessage // function to format a close message payload. CloseMessage = 8 // PingMessage denotes a ping control message. The optional message payload // is UTF-8 encoded text. PingMessage = 9 // PongMessage denotes a ping control message. The optional message payload // is UTF-8 encoded text. PongMessage = 10 )
The message types are defined in RFC 6455, section 11.8.
Variables ¶
var ( // ErrCloseSent is returned when the application writes a message to the // connection after sending a close message. ErrCloseSent = errors.New("websocket: close sent") // ErrReadLimit is returned when reading a message that is larger than the // read limit set for the connection. ErrReadLimit = errors.New("websocket: read limit exceeded") )
var ErrBadHandshake = errors.New("websocket: bad handshake")
ErrBadHandshake is returned when the server response to opening handshake is invalid.
Functions ¶
func FormatCloseMessage ¶
FormatCloseMessage formats closeCode and text as a WebSocket close message.
func Subprotocols ¶
Subprotocols returns the subprotocols requested by the client in the Sec-Websocket-Protocol header.
Types ¶
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn represents a WebSocket connection.
func NewClient ¶
func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error)
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.
func Upgrade ¶
func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error)
Upgrade upgrades the HTTP server connection to the WebSocket protocol.
This function is deprecated, use websocket.Upgrader instead.
The application is responsible for checking the request origin before calling Upgrade. An example implementation of the same origin policy is:
if req.Header.Get("Origin") != "http://"+req.Host { http.Error(w, "Origin not allowed", 403) 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.
func (*Conn) Close ¶
Close closes the underlying network connection without sending or waiting for a close frame.
func (*Conn) NextReader ¶
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.
The NextReader method and the readers returned from the method cannot be accessed by more than one goroutine at a time.
func (*Conn) NextWriter ¶
func (c *Conn) NextWriter(messageType int) (io.WriteCloser, 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.
The NextWriter method and the writers returned from the method cannot be accessed by more than one goroutine at a time.
func (*Conn) ReadJSON ¶
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 Marshal function for details about the conversion of JSON to a Go value.
func (*Conn) ReadMessage ¶
ReadMessage is a helper method for getting a reader using NextReader and reading from that reader to a buffer.
func (*Conn) RemoteAddr ¶
RemoteAddr returns the remote network address.
func (*Conn) SetPingHandler ¶
SetPingHandler sets the handler for ping messages received from the peer. The default ping handler sends a pong to the peer.
func (*Conn) SetPongHandler ¶
SetPongHandler sets then handler for pong messages received from the peer. The default pong handler does nothing.
func (*Conn) SetReadDeadline ¶
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.
func (*Conn) SetReadLimit ¶
SetReadLimit sets the maximum size for a message read from the peer. If a message exceeds the limit, the connection sends a close frame to the peer and returns ErrReadLimit to the application.
func (*Conn) SetWriteDeadline ¶
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
func (*Conn) Subprotocol ¶
Subprotocol returns the negotiated protocol for the connection.
func (*Conn) UnderlyingConn ¶
UnderlyingConn returns the internal net.Conn. This can be used to further modifications to connection specific flags.
func (*Conn) WriteControl ¶
WriteControl writes a control message with the given deadline. The allowed message types are CloseMessage, PingMessage and PongMessage.
type Dialer ¶
type Dialer struct { // NetDial specifies the dial function for creating TCP connections. If // NetDial is nil, net.Dial is used. NetDial func(network, addr string) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with tls.Client. // If nil, the default configuration is used. TLSClientConfig *tls.Config // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration // Input and output buffer sizes. If the buffer size is zero, then a // default value of 4096 is used. ReadBufferSize, WriteBufferSize int // Subprotocols specifies the client's requested subprotocols. Subprotocols []string }
A Dialer contains options for connecting to WebSocket server.
var DefaultDialer *Dialer
DefaultDialer is a dialer with all fields set to the default zero values.
func (*Dialer) Dial ¶
Dial 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).
If the WebSocket handshake fails, ErrBadHandshake is returned along with a non-nil *http.Response so that callers can handle redirects, authentication, etc.
type HandshakeError ¶
type HandshakeError struct {
// contains filtered or unexported fields
}
HandshakeError describes an error with the handshake from the peer.
func (HandshakeError) Error ¶
func (e HandshakeError) Error() string
type Upgrader ¶
type Upgrader struct { // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer // size is zero, then a default value of 4096 is used. The I/O buffer sizes // do not limit the size of the messages that can be sent or received. ReadBufferSize, WriteBufferSize int // Subprotocols specifies the server's supported protocols in order of // preference. If this field is set, then the Upgrade method negotiates a // subprotocol by selecting the first match in this list with a protocol // requested by the client. Subprotocols []string // Error specifies the function for generating HTTP error responses. If Error // is nil, then http.Error is used to generate the HTTP response. Error func(w http.ResponseWriter, r *http.Request, status int, reason error) // CheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, the host in the Origin header must not be set or // must match the host of the request. CheckOrigin func(r *http.Request) bool }
Upgrader specifies parameters for upgrading an HTTP connection to a WebSocket connection.
func (*Upgrader) Upgrade ¶
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error)
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) and the application negotiated subprotocol (Sec-Websocket-Protocol).