Documentation ¶
Overview ¶
Package websocket implements the WebSocket protocol defined in RFC 6455.
Overview ¶
The Conn type represents a WebSocket connection.
A server application calls the Upgrade function to get a pointer to a Conn:
func handler(w http.ResponseWriter, r *http.Request) { conn, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024) if _, ok := err.(websocket.HandshakeError); ok { http.Error(w, "Not a websocket handshake", 400) return } else if err != nil { log.Println(err) return } ... Use conn to send and receive messages. }
WebSocket messages are represented by the io.Reader interface when receiving a message and by the io.WriteCloser interface when sending a message. An application receives a message by calling the Conn.NextReader method and reading the returned io.Reader to EOF. An application sends a message by calling the Conn.NextWriter method and writing the message to the returned io.WriteCloser. The application terminates the message by closing the io.WriteCloser.
The following example shows how to use the connection NextReader and NextWriter method to echo messages:
for { mt, r, err := conn.NextReader() if err != nil { return } w, err := conn.NextWriter(mt) if err != nil { return err } if _, err := io.Copy(w, r); err != nil { return err } if err := w.Close(); err != nil { return err } }
The connection ReadMessage and WriteMessage methods are helpers for reading or writing an entire message in one method call. The following example shows how to echo messages using these connection helper methods:
for { mt, p, err := conn.ReadMessage() if err != nil { return } if _, err := conn.WriteMessaage(mt, p); err != nil { return err } }
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.
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 same types and methods to work with both types of data messages. It is the application's reponsiblity 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.
Index ¶
- Constants
- Variables
- func FormatCloseMessage(closeCode int, text string) []byte
- func ReadJSON(c *Conn, v interface{}) error
- 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) 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) WriteControl(messageType int, data []byte, deadline time.Time) error
- func (c *Conn) WriteMessage(messageType int, data []byte) error
- type HandshakeError
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 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 = errors.New("websocket: close sent") 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 ¶
SetPongHandler sets the handler for FormatCloseMessage formats closeCode and text as a WebSocket close message.
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 (Set-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.
Upgrade returns a HandshakeError if the request is not a WebSocket handshake. Applications should handle errors of this type by replying to the client with an HTTP response.
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 }
Use the responseHeader to specify cookies (Set-Cookie) and the subprotocol (Sec-WebSocket-Protocol).
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) 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 deadline for future calls to NextReader and the io.Reader returned from NextReader. If the deadline is reached, the call will fail with a timeout instead of blocking. A zero value for t means that the methods 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 deadline for future calls to NextWriter and the io.WriteCloser returned from NextWriter. If the deadline is reached, the call will fail with a timeout instead of blocking. A zero value for t means Write will not time out. Even if Write times out, it may return n > 0, indicating that some of the data was successfully written.
func (*Conn) WriteControl ¶
WriteControl writes a control message with the given deadline. The allowed message types are CloseMessage, PingMessage and PongMessage.
type HandshakeError ¶
type HandshakeError struct {
Err string
}
HandshakeError describes an error with the handshake from the peer.
func (HandshakeError) Error ¶
func (e HandshakeError) Error() string