websocket

package module
v0.0.0-...-bc14117 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2017 License: BSD-2-Clause Imports: 20 Imported by: 16

README

Documentation

Index

Constants

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
	CloseTLSHandshake            = 1015
)

Close codes defined in RFC 6455, section 11.7.

View Source
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.

View Source
const (
	StatusContinue           = 100
	StatusSwitchingProtocols = 101

	StatusOK                   = 200
	StatusCreated              = 201
	StatusAccepted             = 202
	StatusNonAuthoritativeInfo = 203
	StatusNoContent            = 204
	StatusResetContent         = 205
	StatusPartialContent       = 206

	StatusMultipleChoices   = 300
	StatusMovedPermanently  = 301
	StatusFound             = 302
	StatusSeeOther          = 303
	StatusNotModified       = 304
	StatusUseProxy          = 305
	StatusTemporaryRedirect = 307

	StatusBadRequest                   = 400
	StatusUnauthorized                 = 401
	StatusPaymentRequired              = 402
	StatusForbidden                    = 403
	StatusNotFound                     = 404
	StatusMethodNotAllowed             = 405
	StatusNotAcceptable                = 406
	StatusProxyAuthRequired            = 407
	StatusRequestTimeout               = 408
	StatusConflict                     = 409
	StatusGone                         = 410
	StatusLengthRequired               = 411
	StatusPreconditionFailed           = 412
	StatusRequestEntityTooLarge        = 413
	StatusRequestURITooLong            = 414
	StatusUnsupportedMediaType         = 415
	StatusRequestedRangeNotSatisfiable = 416
	StatusExpectationFailed            = 417
	StatusTeapot                       = 418
	StatusPreconditionRequired         = 428
	StatusTooManyRequests              = 429
	StatusRequestHeaderFieldsTooLarge  = 431
	StatusUnavailableForLegalReasons   = 451

	StatusInternalServerError           = 500
	StatusNotImplemented                = 501
	StatusBadGateway                    = 502
	StatusServiceUnavailable            = 503
	StatusGatewayTimeout                = 504
	StatusHTTPVersionNotSupported       = 505
	StatusNetworkAuthenticationRequired = 511
)

taken from net/http

Variables

View Source
var DefaultDialer = &Dialer{
	Proxy: http.ProxyFromEnvironment,
}

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

View Source
var ErrBadHandshake = errors.New("websocket: bad handshake")

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

View Source
var ErrCloseSent = errors.New("websocket: close sent")

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

View Source
var ErrReadLimit = errors.New("websocket: read limit exceeded")

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

Functions

func FormatCloseMessage

func FormatCloseMessage(closeCode int, text string) []byte

FormatCloseMessage formats closeCode and text as a WebSocket close message.

func IsCloseError

func IsCloseError(err error, codes ...int) bool

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

func IsUnexpectedCloseError

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.

func IsWebSocketUpgrade

func IsWebSocketUpgrade(ctx *fasthttp.RequestCtx) bool

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

func ReadJSON

func ReadJSON(c *Conn, v interface{}) error

ReadJSON is deprecated, use c.ReadJSON instead.

func Subprotocols

func Subprotocols(ctx *fasthttp.RequestCtx) []string

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

func Upgrade

func Upgrade(ctx *fasthttp.RequestCtx, receiverHandler func(websocket.UnderlineConnection), readBufSize, writeBufSize int) error

Upgrade upgrades the HTTP server connection to the WebSocket protocol.

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 WriteJSON

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

WriteJSON is deprecated, use c.WriteJSON instead.

Types

type CloseError

type CloseError struct {

	// Code is defined in RFC 6455, section 11.7.
	Code int

	// Text is the optional text payload.
	Text string
}

CloseError represents close frame.

func (*CloseError) Error

func (e *CloseError) Error() string

type Conn

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

Conn represents a WebSocket connection.

func NewClient deprecated

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.

Deprecated: Use Dialer instead.

func (*Conn) Close

func (c *Conn) Close() error

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

func (*Conn) Header

func (c *Conn) Header(key string) (value string)

Header returns header by key

func (*Conn) Headers

func (c *Conn) Headers() *fasthttp.RequestHeader

Headers returns the RequestHeader struct

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Conn) NextReader

func (c *Conn) NextReader() (messageType int, r io.Reader, err error)

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.

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.

func (*Conn) ReadJSON

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

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.

func (*Conn) ReadMessage

func (c *Conn) ReadMessage() (messageType int, p []byte, err error)

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

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Conn) SetHeaders

func (c *Conn) SetHeaders(h *fasthttp.RequestHeader)

SetHeaders sets request headers

func (*Conn) SetPingHandler

func (c *Conn) SetPingHandler(h func(appData string) error)

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

func (*Conn) SetPongHandler

func (c *Conn) SetPongHandler(h func(appData string) error)

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

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

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

func (c *Conn) SetReadLimit(limit int64)

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

func (c *Conn) SetWriteDeadline(t time.Time) error

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

func (c *Conn) Subprotocol() string

Subprotocol returns the negotiated protocol for the connection.

func (*Conn) UnderlyingConn

func (c *Conn) UnderlyingConn() net.Conn

UnderlyingConn returns the internal net.Conn. This can be used to further modifications to connection specific flags.

func (*Conn) WriteControl

func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error

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

func (*Conn) WriteJSON

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

WriteJSON writes the JSON encoding of v to the connection.

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

func (*Conn) WriteMessage

func (c *Conn) WriteMessage(messageType int, data []byte) error

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

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)

	// Proxy specifies a function to return a proxy for a given
	// Request. If the function returns a non-nil error, the
	// request is aborted with the provided error.
	// If Proxy is nil or returns a nil *URL, no proxy is used.
	Proxy func(*http.Request) (*url.URL, 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.

func (*Dialer) Dial

func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error)

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, 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 {
	// contains filtered or unexported fields
}

HandshakeError describes an error with the handshake from the peer.

func (HandshakeError) Error

func (e HandshakeError) Error() string

func (HandshakeError) Status

func (e HandshakeError) Status() int

Status returns the status code of this HandshakeError

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

	//Receiver it's the receiver handler, acceps a kataras/go-websocket.UnderlineConnection
	Receiver func(websocket.UnderlineConnection)

	// Headers  if true then the client's headers are copy to the websocket connection
	Headers bool
}

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

func Custom

func Custom(receiverHandler func(websocket.UnderlineConnection), readBufSize, writeBufSize int, copyheaders bool) Upgrader

Custom returns an Upgrader with customized options (readBufSize,writeBuf size int) accepts 3 parameters first parameter is the receiver, think it like a handler which accepts a *websocket.Conn (func *websocket.Conn) second parameter is the readBufSize (int) third parameter is the writeBufSize (int)

func New

func New(receiverHandler func(websocket.UnderlineConnection)) Upgrader

New returns an Upgrader with the default options accepts one parameter the receiver, think it like a handler which accepts a *websocket.Conn (func *websocket.Conn)

func (*Upgrader) Upgrade

func (u *Upgrader) Upgrade(ctx *fasthttp.RequestCtx) 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).

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

Jump to

Keyboard shortcuts

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