Documentation ¶
Index ¶
- Constants
- Variables
- func FormatCloseMessage(closeCode int, text string) []byte
- func IsCloseError(err error, codes ...int) bool
- func IsUnexpectedCloseError(err error, expectedCodes ...int) bool
- type BufferPool
- type ClientUpgrader
- type CloseError
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) CloseHandler() func(code int, text string) error
- func (c *Conn) EnableWriteCompression(enable bool)
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) NetConn() net.Conn
- func (c *Conn) NextReader() (messageType int, r io.Reader, err error)
- func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error)
- func (c *Conn) PingHandler() func(appData string) error
- func (c *Conn) PongHandler() func(appData string) 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) SetCloseHandler(h func(code int, text string) error)
- func (c *Conn) SetCompressionLevel(level int) error
- func (c *Conn) SetPingHandler(h func(appData string) error)
- func (c *Conn) SetPongHandler(h func(appData 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
- func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error
- type HandshakeError
- type HertzHandler
- type HertzUpgrader
- type PreparedMessage
Constants ¶
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.
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 pong 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 ErrBadHandshake = errors.New("websocket: bad handshake")
ErrBadHandshake is returned when the server response to opening handshake is invalid.
var ErrCloseSent = errors.New("websocket: close sent")
ErrCloseSent is returned when the application writes a message to the connection after sending a close message.
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 ¶
FormatCloseMessage formats closeCode and text as a WebSocket close message. An empty message is returned for code CloseNoStatusReceived.
func IsCloseError ¶
IsCloseError returns boolean indicating whether the error is a *CloseError with one of the specified codes.
func IsUnexpectedCloseError ¶
IsUnexpectedCloseError returns boolean indicating whether the error is a *CloseError with a code not in the list of expected codes.
Types ¶
type BufferPool ¶
type BufferPool interface { // Get gets a value from the pool or returns nil if the pool is empty. Get() interface{} // Put adds a value to the pool. 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 ClientUpgrader ¶ added in v0.2.0
type ClientUpgrader struct {
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
// size is zero, then buffers allocated by the HTTP server are used. The
// I/O buffer sizes do not limit the size of the messages that can be sent
// or received.
ReadBufferSize, WriteBufferSize int
// WriteBufferPool is a pool of buffers for write operations. If the value
// is not set, then write buffers are allocated to the connection for the
// lifetime of the connection.
//
// A pool is most useful when the application has a modest volume of writes
// across a large number of connections.
//
// Applications should use a single pool for each unique value of
// WriteBufferSize.
WriteBufferPool BufferPool
// EnableCompression specify if the server should attempt to negotiate per
// message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
}
ClientUpgrader is a helper for upgrading hertz http response to websocket conn. See ExampleClient for usage
func (*ClientUpgrader) PrepareRequest ¶ added in v0.2.0
func (p *ClientUpgrader) PrepareRequest(req *protocol.Request)
PrepareRequest prepares request for websocket
It adds headers for websocket, and it must be called BEFORE sending http request via cli.DoXXX
func (*ClientUpgrader) UpgradeResponse ¶ added in v0.2.0
func (p *ClientUpgrader) UpgradeResponse(req *protocol.Request, resp *protocol.Response) (*Conn, error)
UpgradeResponse upgrades a response to websocket conn
It returns Conn if success. ErrBadHandshake is returned if headers go wrong. This method must be called after PrepareRequest and (*.Client).DoXXX
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 a close message.
func (*CloseError) Error ¶
func (e *CloseError) Error() string
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
The Conn type represents a WebSocket connection.
func (*Conn) Close ¶
Close closes the underlying network connection without sending or waiting for a close message.
func (*Conn) CloseHandler ¶
CloseHandler returns the current close handler
func (*Conn) EnableWriteCompression ¶
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.
func (*Conn) NetConn ¶
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.
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.
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.
All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and PongMessage) are supported.
func (*Conn) PingHandler ¶
PingHandler returns the current ping handler
func (*Conn) PongHandler ¶
PongHandler returns the current pong handler
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 Unmarshal 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) SetCloseHandler ¶
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.
func (*Conn) SetCompressionLevel ¶
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.
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 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.
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. Deprecated: Use the NetConn method.
func (*Conn) WriteControl ¶
WriteControl writes a control message with the given deadline. The allowed message types are CloseMessage, PingMessage and PongMessage.
func (*Conn) WriteJSON ¶
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.
func (*Conn) WriteMessage ¶
WriteMessage is a helper method for getting a writer using NextWriter, writing the message and closing the writer.
func (*Conn) WritePreparedMessage ¶
func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error
WritePreparedMessage writes prepared message into connection.
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 HertzHandler ¶
type HertzHandler func(*Conn)
HertzHandler receives a websocket connection after the handshake has been completed. This must be provided.
type HertzUpgrader ¶
type HertzUpgrader struct { // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer // size is zero, then buffers allocated by the HTTP server are used. The // I/O buffer sizes do not limit the size of the messages that can be sent // or received. ReadBufferSize, WriteBufferSize int // WriteBufferPool is a pool of buffers for write operations. If the value // is not set, then write buffers are allocated to the connection for the // lifetime of the connection. // // A pool is most useful when the application has a modest volume of writes // across a large number of connections. // // Applications should use a single pool for each unique value of // WriteBufferSize. WriteBufferPool BufferPool // Subprotocols specifies the server's supported protocols in order of // preference. If this field is not nil, then the Upgrade method negotiates a // subprotocol by selecting the first match in this list with a protocol // requested by the client. If there's no match, then no protocol is // negotiated (the Sec-Websocket-Protocol header is not included in the // handshake response). 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(ctx *app.RequestContext, status int, reason error) // CheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, then a safe default is used: return false if the // Origin request header is present and the origin host is not equal to // request Host header. // // A CheckOrigin function should carefully validate the request origin to // prevent cross-site request forgery. CheckOrigin func(ctx *app.RequestContext) bool // EnableCompression specify if the server should attempt to negotiate per // message compression (RFC 7692). Setting this value to true does not // guarantee that compression will be supported. Currently only "no context // takeover" modes are supported. EnableCompression bool }
HertzUpgrader specifies parameters for upgrading an HTTP connection to a WebSocket connection.
func (*HertzUpgrader) Upgrade ¶
func (u *HertzUpgrader) Upgrade(ctx *app.RequestContext, handler HertzHandler) 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.
type PreparedMessage ¶
type PreparedMessage struct {
// contains filtered or unexported fields
}
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.
func NewPreparedMessage ¶
func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error)
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.