package ws
Import Path
github.com/gobwas/ws (on go.dev)
Dependency Relation
imports 22 packages, and imported by 2 packages
Involved Source Files
check.go
cipher.go
dialer.go
dialer_tls_go18.go
Package ws implements a client and server for the WebSocket protocol as
specified in RFC 6455.
The main purpose of this package is to provide simple low-level API for
efficient work with protocol.
Overview.
Upgrade to WebSocket (or WebSocket handshake) can be done in two ways.
The first way is to use `net/http` server:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
conn, _, _, err := ws.UpgradeHTTP(r, w)
})
The second and much more efficient way is so-called "zero-copy upgrade". It
avoids redundant allocations and copying of not used headers or other request
data. User decides by himself which data should be copied.
ln, err := net.Listen("tcp", ":8080")
if err != nil {
// handle error
}
conn, err := ln.Accept()
if err != nil {
// handle error
}
handshake, err := ws.Upgrade(conn)
if err != nil {
// handle error
}
For customization details see `ws.Upgrader` documentation.
After WebSocket handshake you can work with connection in multiple ways.
That is, `ws` does not force the only one way of how to work with WebSocket:
header, err := ws.ReadHeader(conn)
if err != nil {
// handle err
}
buf := make([]byte, header.Length)
_, err := io.ReadFull(conn, buf)
if err != nil {
// handle err
}
resp := ws.NewBinaryFrame([]byte("hello, world!"))
if err := ws.WriteFrame(conn, frame); err != nil {
// handle err
}
As you can see, it stream friendly:
const N = 42
ws.WriteHeader(ws.Header{
Fin: true,
Length: N,
OpCode: ws.OpBinary,
})
io.CopyN(conn, rand.Reader, N)
Or:
header, err := ws.ReadHeader(conn)
if err != nil {
// handle err
}
io.CopyN(ioutil.Discard, conn, header.Length)
For more info see the documentation.
errors.go
frame.go
hijack_go120.go
http.go
nonce.go
read.go
server.go
util.go
util_unsafe.go
write.go
Package-Level Type Names (total 19)
ConnectionRejectedError represents a rejection of connection during
WebSocket handshake error.
It can be returned by Upgrader's On* hooks to indicate that WebSocket
handshake should be rejected.
Error implements error interface.
(*ConnectionRejectedError) StatusCode() int
*ConnectionRejectedError : error
Dialer contains options for establishing websocket connection to an url.
Extensions is the list of extensions that client wants to speak.
Note that if server decides to use some of this extensions, Dial() will
return Handshake struct containing a slice of items, which are the
shallow copies of the items from this list. That is, internals of
Extensions items are shared during Dial().
See https://tools.ietf.org/html/rfc6455#section-4.1
See https://tools.ietf.org/html/rfc6455#section-9.1
Header is an optional HandshakeHeader instance that could be used to
write additional headers to the handshake request.
It used instead of any key-value mappings to avoid allocations in user
land.
NetDial is the function that is used to get plain tcp connection.
If it is not nil, then it is used instead of net.Dialer.
OnHeader is the callback that will be called after successful parsing of
header, that is not used during WebSocket handshake procedure. That is,
it will be called with non-websocket headers, which could be relevant
for application-level logic.
The arguments are only valid until the callback returns.
Returned value could be used to prevent processing response.
OnStatusError is the callback that will be called after receiving non
"101 Continue" HTTP response status. It receives an io.Reader object
representing server response bytes. That is, it gives ability to parse
HTTP response somehow (probably with http.ReadResponse call) and make a
decision of further logic.
The arguments are only valid until the callback returns.
Protocols is the list of subprotocols that the client wants to speak,
ordered by preference.
See https://tools.ietf.org/html/rfc6455#section-4.1
ReadBufferSize and WriteBufferSize is an I/O buffer sizes.
They used to read and write http data while upgrading to WebSocket.
Allocated buffers are pooled with sync.Pool to avoid extra allocations.
If a size is zero then default value is used.
TLSClient is the callback that will be called after successful dial with
received connection and its remote host name. If it is nil, then the
default tls.Client() will be used.
If it is not nil, then TLSConfig field is ignored.
TLSConfig is passed to tls.Client() to start TLS over established
connection. If TLSClient is not nil, then it is ignored. If TLSConfig is
non-nil and its ServerName is empty, then for every Dial() it will be
cloned and appropriate ServerName will be set.
Timeout is the maximum amount of time a Dial() will wait for a connect
and an handshake to complete.
The default is no timeout.
WrapConn is the optional callback that will be called when connection is
ready for an i/o. That is, it will be called after successful dial and
TLS initialization (for "wss" schemes). It may be helpful for different
user land purposes such as end to end encryption.
Note that for debugging purposes of an http handshake (e.g. sent request
and received response), there is an wsutil.DebugDialer struct.
ReadBufferSize and WriteBufferSize is an I/O buffer sizes.
They used to read and write http data while upgrading to WebSocket.
Allocated buffers are pooled with sync.Pool to avoid extra allocations.
If a size is zero then default value is used.
Dial connects to the url host and upgrades connection to WebSocket.
If server has sent frames right after successful handshake then returned
buffer will be non-nil. In other cases buffer is always nil. For better
memory efficiency received non-nil bufio.Reader should be returned to the
inner pool with PutReader() function after use.
Note that Dialer does not implement IDNA (RFC5895) logic as net/http does.
If you want to dial non-ascii host name, take care of its name serialization
avoiding bad request issues. For more info see net/http Request.Write()
implementation, especially cleanHost() function.
Upgrade writes an upgrade request to the given io.ReadWriter conn at given
url u and reads a response from it.
It is a caller responsibility to manage I/O deadlines on conn.
It returns handshake info and some bytes which could be written by the peer
right after response and be caught by us during buffered read.
var DefaultDialer
Frame represents websocket frame.
See https://tools.ietf.org/html/rfc6455#section-5.2
Header Header
Payload []byte
func MaskFrame(f Frame) Frame
func MaskFrameInPlace(f Frame) Frame
func MaskFrameInPlaceWith(f Frame, m [4]byte) Frame
func MaskFrameWith(f Frame, mask [4]byte) Frame
func MustReadFrame(r io.Reader) Frame
func NewBinaryFrame(p []byte) Frame
func NewCloseFrame(p []byte) Frame
func NewFrame(op OpCode, fin bool, p []byte) Frame
func NewPingFrame(p []byte) Frame
func NewPongFrame(p []byte) Frame
func NewTextFrame(p []byte) Frame
func ReadFrame(r io.Reader) (f Frame, err error)
func UnmaskFrame(f Frame) Frame
func UnmaskFrameInPlace(f Frame) Frame
func CompileFrame(f Frame) (bts []byte, err error)
func MaskFrame(f Frame) Frame
func MaskFrameInPlace(f Frame) Frame
func MaskFrameInPlaceWith(f Frame, m [4]byte) Frame
func MaskFrameWith(f Frame, mask [4]byte) Frame
func MustCompileFrame(f Frame) []byte
func MustWriteFrame(w io.Writer, f Frame)
func UnmaskFrame(f Frame) Frame
func UnmaskFrameInPlace(f Frame) Frame
func WriteFrame(w io.Writer, f Frame) error
Handshake represents handshake result.
Extensions is the list of negotiated extensions.
Protocol is the subprotocol selected during handshake.
func Dial(ctx context.Context, urlstr string) (net.Conn, *bufio.Reader, Handshake, error)
func Upgrade(conn io.ReadWriter) (Handshake, error)
func UpgradeHTTP(r *http.Request, w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, Handshake, error)
func Dialer.Dial(ctx context.Context, urlstr string) (conn net.Conn, br *bufio.Reader, hs Handshake, err error)
func Dialer.Upgrade(conn io.ReadWriter, u *url.URL) (br *bufio.Reader, hs Handshake, err error)
func HTTPUpgrader.Upgrade(r *http.Request, w http.ResponseWriter) (conn net.Conn, rw *bufio.ReadWriter, hs Handshake, err error)
func Upgrader.Upgrade(conn io.ReadWriter) (hs Handshake, err error)
func github.com/gobwas/ws/wsutil.(*DebugDialer).Dial(ctx context.Context, urlstr string) (conn net.Conn, br *bufio.Reader, hs Handshake, err error)
func github.com/gobwas/ws/wsutil.(*DebugUpgrader).Upgrade(conn io.ReadWriter) (hs Handshake, err error)
HandshakeHeader is the interface that writes both upgrade request or
response headers into a given io.Writer.
( HandshakeHeader) WriteTo(w io.Writer) (n int64, err error)
HandshakeHeaderBytes
HandshakeHeaderFunc
HandshakeHeaderHTTP
HandshakeHeaderString
github.com/apache/thrift/lib/go/thrift.TBufferedTransport
github.com/apache/thrift/lib/go/thrift.TMemoryBuffer
*github.com/bits-and-blooms/bitset.BitSet
github.com/coreos/etcd/pkg/fileutil.LockedFile
*github.com/klauspost/compress/gzip.Reader
*github.com/klauspost/compress/zstd.Decoder
*github.com/libp2p/go-buffer-pool.Buffer
github.com/libp2p/go-libp2p/p2p/transport/tcpreuse/internal/sampledconn.ManetTCPConnInterface (interface)
*github.com/ncruces/go-sqlite3.Blob
*github.com/pierrec/lz4/v4.Reader
*github.com/pion/stun.Message
*github.com/pion/stun/v3.Message
*github.com/polarsignals/wal/fs.File
*github.com/RoaringBitmap/roaring.Bitmap
*bufio.Reader
bufio.ReadWriter
*bytes.Buffer
*bytes.Reader
*go.etcd.io/bbolt.Tx
gonum.org/v1/plot/vg.CanvasWriterTo (interface)
io.WriterTo (interface)
*net.Buffers
*net.TCPConn
*os.File
*runtime/trace.FlightRecorder
*strings.Reader
HandshakeHeader : io.WriterTo
func RejectionHeader(h HandshakeHeader) RejectOption
HandshakeHeaderBytes is an adapter to allow the use of headers represented
by ordinary slice of bytes as HandshakeHeader.
WriteTo implements HandshakeHeader (and io.WriterTo) interface.
HandshakeHeaderBytes : HandshakeHeader
HandshakeHeaderBytes : io.WriterTo
HandshakeHeaderFunc is an adapter to allow the use of headers represented by
ordinary function as HandshakeHeader.
WriteTo implements HandshakeHeader (and io.WriterTo) interface.
HandshakeHeaderFunc : HandshakeHeader
HandshakeHeaderFunc : io.WriterTo
HandshakeHeaderHTTP is an adapter to allow the use of http.Header as
HandshakeHeader.
WriteTo implements HandshakeHeader (and io.WriterTo) interface.
HandshakeHeaderHTTP : HandshakeHeader
HandshakeHeaderHTTP : io.WriterTo
HandshakeHeaderString is an adapter to allow the use of headers represented
by ordinary string as HandshakeHeader.
WriteTo implements HandshakeHeader (and io.WriterTo) interface.
HandshakeHeaderString : HandshakeHeader
HandshakeHeaderString : io.WriterTo
Header represents websocket frame header.
See https://tools.ietf.org/html/rfc6455#section-5.2
Fin bool
Length int64
Mask [4]byte
Masked bool
OpCode OpCode
Rsv byte
Rsv1 reports whether the header has first rsv bit set.
Rsv2 reports whether the header has second rsv bit set.
Rsv3 reports whether the header has third rsv bit set.
func ReadHeader(r io.Reader) (h Header, err error)
func github.com/gobwas/ws/wsutil.NextReader(r io.Reader, s State) (Header, io.Reader, error)
func github.com/gobwas/ws/wsutil.(*Reader).NextFrame() (hdr Header, err error)
func github.com/gobwas/ws/wsutil.RecvExtension.UnsetBits(Header) (Header, error)
func github.com/gobwas/ws/wsutil.RecvExtensionFunc.UnsetBits(h Header) (Header, error)
func github.com/gobwas/ws/wsutil.SendExtension.SetBits(Header) (Header, error)
func github.com/gobwas/ws/wsutil.SendExtensionFunc.SetBits(h Header) (Header, error)
func CheckHeader(h Header, s State) error
func HeaderSize(h Header) (n int)
func WriteHeader(w io.Writer, h Header) error
func github.com/gobwas/ws/wsutil.ControlHandler.Handle(h Header) error
func github.com/gobwas/ws/wsutil.ControlHandler.HandleClose(h Header) error
func github.com/gobwas/ws/wsutil.ControlHandler.HandlePing(h Header) error
func github.com/gobwas/ws/wsutil.ControlHandler.HandlePong(h Header) error
func github.com/gobwas/ws/wsutil.RecvExtension.UnsetBits(Header) (Header, error)
func github.com/gobwas/ws/wsutil.RecvExtensionFunc.UnsetBits(h Header) (Header, error)
func github.com/gobwas/ws/wsutil.SendExtension.SetBits(Header) (Header, error)
func github.com/gobwas/ws/wsutil.SendExtensionFunc.SetBits(h Header) (Header, error)
HTTPUpgrader contains options for upgrading connection to websocket from
net/http Handler arguments.
Extension is the select function that is used to select extensions from
list requested by client. If this field is set, then the all matched
extensions are sent to a client as negotiated.
Deprecated: use Negotiate instead.
Header is an optional http.Header mapping that could be used to
write additional headers to the handshake response.
Note that if present, it will be written in any result of handshake.
Negotiate is the callback that is used to negotiate extensions from
the client's offer. If this field is set, then the returned non-zero
extensions are sent to the client as accepted extensions in the
response.
The argument is only valid until the Negotiate callback returns.
If returned error is non-nil then connection is rejected and response is
sent with appropriate HTTP error code and body set to error message.
RejectConnectionError could be used to get more control on response.
Protocol is the select function that is used to select subprotocol from
list requested by client. If this field is set, then the first matched
protocol is sent to a client as negotiated.
Timeout is the maximum amount of time an Upgrade() will spent while
writing handshake response.
The default is no timeout.
Upgrade upgrades http connection to the websocket connection.
It hijacks net.Conn from w and returns received net.Conn and
bufio.ReadWriter. On successful handshake it returns Handshake struct
describing handshake info.
var DefaultHTTPUpgrader
OpCode represents operation code.
IsControl checks whether the c is control operation code.
See https://tools.ietf.org/html/rfc6455#section-5.5
IsData checks whether the c is data operation code.
See https://tools.ietf.org/html/rfc6455#section-5.6
IsReserved checks whether the c is reserved operation code.
See https://tools.ietf.org/html/rfc6455#section-5.2
func github.com/gobwas/ws/wsutil.ReadClientData(rw io.ReadWriter) ([]byte, OpCode, error)
func github.com/gobwas/ws/wsutil.ReadData(rw io.ReadWriter, s State) ([]byte, OpCode, error)
func github.com/gobwas/ws/wsutil.ReadServerData(rw io.ReadWriter) ([]byte, OpCode, error)
func NewFrame(op OpCode, fin bool, p []byte) Frame
func github.com/gobwas/ws/wsutil.GetWriter(dest io.Writer, state State, op OpCode, n int) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NewControlWriter(dest io.Writer, state State, op OpCode) *wsutil.ControlWriter
func github.com/gobwas/ws/wsutil.NewControlWriterBuffer(dest io.Writer, state State, op OpCode, buf []byte) *wsutil.ControlWriter
func github.com/gobwas/ws/wsutil.NewWriter(dest io.Writer, state State, op OpCode) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NewWriterBuffer(dest io.Writer, state State, op OpCode, buf []byte) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NewWriterBufferSize(dest io.Writer, state State, op OpCode, n int) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NewWriterSize(dest io.Writer, state State, op OpCode, n int) *wsutil.Writer
func github.com/gobwas/ws/wsutil.WriteClientMessage(w io.Writer, op OpCode, p []byte) error
func github.com/gobwas/ws/wsutil.WriteMessage(w io.Writer, s State, op OpCode, p []byte) error
func github.com/gobwas/ws/wsutil.WriteServerMessage(w io.Writer, op OpCode, p []byte) error
func github.com/gobwas/ws/wsutil.(*Writer).Reset(dest io.Writer, state State, op OpCode)
func github.com/gobwas/ws/wsutil.(*Writer).ResetOp(op OpCode)
const OpBinary
const OpClose
const OpContinuation
const OpPing
const OpPong
const OpText
ProtocolError describes error during checking/parsing websocket frames or
headers.
Error implements error interface.
ProtocolError : error
var ErrProtocolContinuationExpected
var ErrProtocolContinuationUnexpected
var ErrProtocolControlNotFinal
var ErrProtocolControlPayloadOverflow
var ErrProtocolInvalidUTF8
var ErrProtocolMaskRequired
var ErrProtocolMaskUnexpected
var ErrProtocolNonZeroRsv
var ErrProtocolOpCodeReserved
var ErrProtocolStatusCodeApplicationLevel
var ErrProtocolStatusCodeNoMeaning
var ErrProtocolStatusCodeNotInUse
var ErrProtocolStatusCodeUnknown
RejectOption represents an option used to control the way connection is
rejected.
func RejectionHeader(h HandshakeHeader) RejectOption
func RejectionReason(reason string) RejectOption
func RejectionStatus(code int) RejectOption
func RejectConnectionError(options ...RejectOption) error
State represents state of websocket endpoint.
It used by some functions to be more strict when checking compatibility with RFC6455.
Clear disables v state on s.
ClientSide reports whether state represents client side.
Extended reports whether state is extended.
Fragmented reports whether state is fragmented.
Is checks whether the s has v enabled.
ServerSide reports whether states represents server side.
Set enables v state on s.
func State.Clear(v State) State
func State.Set(v State) State
func CheckHeader(h Header, s State) error
func State.Clear(v State) State
func State.Is(v State) bool
func State.Set(v State) State
func github.com/gobwas/ws/wsutil.ControlFrameHandler(w io.Writer, state State) wsutil.FrameHandlerFunc
func github.com/gobwas/ws/wsutil.GetWriter(dest io.Writer, state State, op OpCode, n int) *wsutil.Writer
func github.com/gobwas/ws/wsutil.HandleControlMessage(conn io.Writer, state State, msg wsutil.Message) error
func github.com/gobwas/ws/wsutil.NewControlWriter(dest io.Writer, state State, op OpCode) *wsutil.ControlWriter
func github.com/gobwas/ws/wsutil.NewControlWriterBuffer(dest io.Writer, state State, op OpCode, buf []byte) *wsutil.ControlWriter
func github.com/gobwas/ws/wsutil.NewReader(r io.Reader, s State) *wsutil.Reader
func github.com/gobwas/ws/wsutil.NewWriter(dest io.Writer, state State, op OpCode) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NewWriterBuffer(dest io.Writer, state State, op OpCode, buf []byte) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NewWriterBufferSize(dest io.Writer, state State, op OpCode, n int) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NewWriterSize(dest io.Writer, state State, op OpCode, n int) *wsutil.Writer
func github.com/gobwas/ws/wsutil.NextReader(r io.Reader, s State) (Header, io.Reader, error)
func github.com/gobwas/ws/wsutil.ReadData(rw io.ReadWriter, s State) ([]byte, OpCode, error)
func github.com/gobwas/ws/wsutil.ReadMessage(r io.Reader, s State, m []wsutil.Message) ([]wsutil.Message, error)
func github.com/gobwas/ws/wsutil.WriteMessage(w io.Writer, s State, op OpCode, p []byte) error
func github.com/gobwas/ws/wsutil.(*Writer).Reset(dest io.Writer, state State, op OpCode)
const StateClientSide
const StateExtended
const StateFragmented
const StateServerSide
StatusCode represents the encoded reason for closure of websocket connection.
There are few helper methods on StatusCode that helps to define a range in
which given code is lay in. accordingly to ranges defined in specification.
See https://tools.ietf.org/html/rfc6455#section-7.4
Empty reports whether the code is empty.
Empty code has no any meaning neither app level codes nor other.
This method is useful just to check that code is golang default value 0.
In reports whether the code is defined in given range.
IsApplicationSpec reports whether the code should be defined by
application, framework or libraries specification.
IsNotUsed reports whether the code is predefined in not used range.
IsPrivateSpec reports whether the code should be defined privately.
IsProtocolDefined reports whether the code is already defined by protocol specification.
IsProtocolReserved reports whether the code is defined by protocol specification
to be reserved only for application usage purpose.
IsProtocolSpec reports whether the code should be defined by protocol specification.
func ParseCloseFrameData(payload []byte) (code StatusCode, reason string)
func ParseCloseFrameDataUnsafe(payload []byte) (code StatusCode, reason string)
func CheckCloseFrameData(code StatusCode, reason string) error
func NewCloseFrameBody(code StatusCode, reason string) []byte
func PutCloseFrameBody(p []byte, code StatusCode, reason string)
const StatusAbnormalClosure
const StatusGoingAway
const StatusInternalServerError
const StatusInvalidFramePayloadData
const StatusMandatoryExt
const StatusMessageTooBig
const StatusNoMeaningYet
const StatusNormalClosure
const StatusNoStatusRcvd
const StatusPolicyViolation
const StatusProtocolError
const StatusTLSHandshake
const StatusUnsupportedData
StatusCodeRange describes range of StatusCode values.
Max StatusCode
Min StatusCode
func StatusCode.In(r StatusCodeRange) bool
var StatusRangeApplication
var StatusRangeNotInUse
var StatusRangePrivate
var StatusRangeProtocol
StatusError contains an unexpected status-line code from the server.
( StatusError) Error() string
StatusError : error
Upgrader contains options for upgrading connection to websocket.
Extension is a select function that is used to select extensions
from list requested by client. If this field is set, then the all matched
extensions are sent to a client as negotiated.
Note that Extension may be called multiple times and implementations
must track uniqueness of accepted extensions manually.
The argument is only valid until the callback returns.
According to the RFC6455 order of extensions passed by a client is
significant. That is, returning true from this function means that no
other extension with the same name should be checked because server
accepted the most preferable extension right now:
"Note that the order of extensions is significant. Any interactions between
multiple extensions MAY be defined in the documents defining the extensions.
In the absence of such definitions, the interpretation is that the header
fields listed by the client in its request represent a preference of the
header fields it wishes to use, with the first options listed being most
preferable."
Deprecated: use Negotiate instead.
ExtensionCustom allow user to parse Sec-WebSocket-Extensions header
manually.
If ExtensionCustom() decides to accept received extension, it must
append appropriate option to the given slice of httphead.Option.
It returns results of append() to the given slice and a flag that
reports whether given header value is wellformed or not.
Note that ExtensionCustom may be called multiple times and
implementations must track uniqueness of accepted extensions manually.
Note that returned options should be valid until Upgrade returns.
If ExtensionCustom is set, it used instead of Extension function.
Header is an optional HandshakeHeader instance that could be used to
write additional headers to the handshake response.
It used instead of any key-value mappings to avoid allocations in user
land.
Note that if present, it will be written in any result of handshake.
Negotiate is the callback that is used to negotiate extensions from
the client's offer. If this field is set, then the returned non-zero
extensions are sent to the client as accepted extensions in the
response.
The argument is only valid until the Negotiate callback returns.
If returned error is non-nil then connection is rejected and response is
sent with appropriate HTTP error code and body set to error message.
RejectConnectionError could be used to get more control on response.
OnBeforeUpgrade is a callback that will be called before sending
successful upgrade response.
Setting OnBeforeUpgrade allows user to make final application-level
checks and decide whether this connection is allowed to successfully
upgrade to WebSocket.
It must return non-nil either HandshakeHeader or error and never both.
If returned error is non-nil then connection is rejected and response is
sent with appropriate HTTP error code and body set to error message.
RejectConnectionError could be used to get more control on response.
OnHeader is a callback that will be called after successful parsing of
header, that is not used during WebSocket handshake procedure. That is,
it will be called with non-websocket headers, which could be relevant
for application-level logic.
The arguments are only valid until the callback returns.
If returned error is non-nil then connection is rejected and response is
sent with appropriate HTTP error code and body set to error message.
RejectConnectionError could be used to get more control on response.
OnHost is a callback that will be called after "Host" header successful
parsing.
It is separated from OnHeader callback because the Host header must be
present in each request since HTTP/1.1. Thus Host header is non-optional
and required for every WebSocket handshake.
The arguments are only valid until the callback returns.
If returned error is non-nil then connection is rejected and response is
sent with appropriate HTTP error code and body set to error message.
RejectConnectionError could be used to get more control on response.
OnRequest is a callback that will be called after request line
successful parsing.
The arguments are only valid until the callback returns.
If returned error is non-nil then connection is rejected and response is
sent with appropriate HTTP error code and body set to error message.
RejectConnectionError could be used to get more control on response.
Protocol is a select function that is used to select subprotocol
from list requested by client. If this field is set, then the first matched
protocol is sent to a client as negotiated.
The argument is only valid until the callback returns.
ProtocolCustrom allow user to parse Sec-WebSocket-Protocol header manually.
Note that returned bytes must be valid until Upgrade returns.
If ProtocolCustom is set, it used instead of Protocol function.
ReadBufferSize and WriteBufferSize is an I/O buffer sizes.
They used to read and write http data while upgrading to WebSocket.
Allocated buffers are pooled with sync.Pool to avoid extra allocations.
If a size is zero then default value is used.
Usually it is useful to set read buffer size bigger than write buffer
size because incoming request could contain long header values, such as
Cookie. Response, in other way, could be big only if user write multiple
custom headers. Usually response takes less than 256 bytes.
ReadBufferSize and WriteBufferSize is an I/O buffer sizes.
They used to read and write http data while upgrading to WebSocket.
Allocated buffers are pooled with sync.Pool to avoid extra allocations.
If a size is zero then default value is used.
Usually it is useful to set read buffer size bigger than write buffer
size because incoming request could contain long header values, such as
Cookie. Response, in other way, could be big only if user write multiple
custom headers. Usually response takes less than 256 bytes.
Upgrade zero-copy upgrades connection to WebSocket. It interprets given conn
as connection with incoming HTTP Upgrade request.
It is a caller responsibility to manage i/o timeouts on conn.
Non-nil error means that request for the WebSocket upgrade is invalid or
malformed and usually connection should be closed.
Even when error is non-nil Upgrade will write appropriate response into
connection in compliance with RFC.
var DefaultUpgrader
Package-Level Functions (total 41)
CheckCloseFrameData checks received close information
to be valid RFC6455 compatible close info.
Note that code.Empty() or code.IsAppLevel() will raise error.
If endpoint sends close frame without status code (with frame.Length = 0),
application should not check its payload.
CheckHeader checks h to contain valid header data for given state s.
Note that zero state (0) means that state is clean,
neither server or client side, nor fragmented, nor extended.
Cipher applies XOR cipher to the payload using mask.
Offset is used to cipher chunked data (e.g. in io.Reader implementations).
To convert masked data into unmasked data, or vice versa, the following
algorithm is applied. The same algorithm applies regardless of the
direction of the translation, e.g., the same steps are applied to
mask the data as to unmask the data.
CompileFrame returns byte representation of given frame.
In terms of memory consumption it is useful to precompile static frames
which are often used.
Dial is like Dialer{}.Dial().
HeaderSize returns number of bytes that are needed to encode given header.
It returns -1 if header is malformed.
MaskFrame masks frame and returns frame with masked payload and Mask header's field set.
Note that it copies f payload to prevent collisions.
For less allocations you could use MaskFrameInPlace or construct frame manually.
MaskFrameInPlace masks frame and returns frame with masked payload and Mask
header's field set.
Note that it applies xor cipher to f.Payload without copying, that is, it
modifies f.Payload inplace.
MaskFrameInPlaceWith masks frame with given mask and returns frame
with masked payload and Mask header's field set.
Note that it applies xor cipher to f.Payload without copying, that is, it
modifies f.Payload inplace.
MaskFrameWith masks frame with given mask and returns frame
with masked payload and Mask header's field set.
Note that it copies f payload to prevent collisions.
For less allocations you could use MaskFrameInPlaceWith or construct frame manually.
MustCompileFrame is like CompileFrame but panics if frame can not be
encoded.
MustReadFrame is like ReadFrame but panics if frame can not be read.
MustWriteFrame is like WriteFrame but panics if frame can not be read.
NewBinaryFrame creates binary frame with p as payload.
Note that p is not copied.
NewCloseFrame creates close frame with given close body.
Note that p is not copied.
Note that p must have length of MaxControlFramePayloadSize bytes or less due
to RFC.
NewCloseFrameBody encodes a closure code and a reason into a binary
representation.
It returns slice which is at most MaxControlFramePayloadSize bytes length.
If the reason is too big it will be cropped to fit the limit defined by the
spec.
See https://tools.ietf.org/html/rfc6455#section-5.5
NewFrame creates frame with given operation code,
flag of completeness and payload bytes.
NewMask creates new random mask.
NewPingFrame creates ping frame with p as payload.
Note that p is not copied.
Note that p must have length of MaxControlFramePayloadSize bytes or less due
to RFC.
NewPongFrame creates pong frame with p as payload.
Note that p is not copied.
Note that p must have length of MaxControlFramePayloadSize bytes or less due
to RFC.
NewTextFrame creates text frame with p as payload.
Note that p is not copied.
ParseCloseFrameData parses close frame status code and closure reason if any provided.
If there is no status code in the payload
the empty status code is returned (code.Empty()) with empty string as a reason.
ParseCloseFrameDataUnsafe is like ParseCloseFrameData except the thing
that it does not copies payload bytes into reason, but prepares unsafe cast.
PutCloseFrameBody encodes code and reason into buf.
It will panic if the buffer is too small to accommodate a code or a reason.
PutCloseFrameBody does not check buffer to be RFC compliant, but note that
by RFC it must be at most MaxControlFramePayloadSize.
PutReader returns bufio.Reader instance to the inner reuse pool.
It is useful in rare cases, when Dialer.Dial() returns non-nil buffer which
contains unprocessed buffered data, that was sent by the server quickly
right after handshake.
ReadFrame reads a frame from r.
It is not designed for high optimized use case cause it makes allocation
for frame.Header.Length size inside to read frame payload into.
Note that ReadFrame does not unmask payload.
ReadHeader reads a frame header from r.
RejectConnectionError constructs an error that could be used to control the
way handshake is rejected by Upgrader.
RejectionHeader returns an option that makes connection to be rejected with
given HTTP headers.
RejectionReason returns an option that makes connection to be rejected with
given reason.
RejectionStatus returns an option that makes connection to be rejected with
given HTTP status code.
Rsv creates rsv byte representation from bits.
RsvBits returns rsv bits from bytes representation.
SelectEqual creates accept function that could be used as Protocol/Extension
select during upgrade.
SelectFromSlice creates accept function that could be used as Protocol/Extension
select during upgrade.
UnmaskFrame unmasks frame and returns frame with unmasked payload and Mask
header's field cleared.
Note that it copies f payload.
UnmaskFrameInPlace unmasks frame and returns frame with unmasked payload and
Mask header's field cleared.
Note that it applies xor cipher to f.Payload without copying, that is, it
modifies f.Payload inplace.
Upgrade is like Upgrader{}.Upgrade().
UpgradeHTTP is like HTTPUpgrader{}.Upgrade().
WriteFrame writes frame binary representation into w.
WriteHeader writes header binary representation into w.
Package-Level Variables (total 51)
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
Compiled control frames for common use cases.
For construct-serialize optimizations.
DefaultDialer is dialer that holds no options and is used by Dial function.
DefaultHTTPUpgrader is an HTTPUpgrader that holds no options and is used by
UpgradeHTTP function.
DefaultUpgrader is an Upgrader that holds no options and is used by Upgrade
function.
Errors used by both client and server when preparing WebSocket handshake.
Errors used by the websocket client.
Errors used by both client and server when preparing WebSocket handshake.
Errors used by both client and server when preparing WebSocket handshake.
Errors used by both client and server when preparing WebSocket handshake.
Errors used by both client and server when preparing WebSocket handshake.
Errors used by both client and server when preparing WebSocket handshake.
Errors used by both client and server when preparing WebSocket handshake.
Errors used by the websocket client.
Errors used by the websocket client.
Errors used by both client and server when preparing WebSocket handshake.
ErrHandshakeUpgradeRequired is returned by Upgrader to indicate that
connection is rejected because given WebSocket version is malformed.
According to RFC6455:
If this version does not match a version understood by the server, the
server MUST abort the WebSocket handshake described in this section and
instead send an appropriate HTTP error code (such as 426 Upgrade Required)
and a |Sec-WebSocket-Version| header field indicating the version(s) the
server is capable of understanding.
Errors used by frame reader.
Errors used by frame reader.
ErrMalformedRequest is returned when HTTP request can not be parsed.
ErrMalformedResponse is returned by Dialer to indicate that server response
can not be parsed.
ErrNotHijacker is an error returned when http.ResponseWriter does not
implement http.Hijacker interface.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Errors used by the protocol checkers.
Status code ranges defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.2
Status code ranges defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.2
Status code ranges defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.2
Status code ranges defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.2
Package-Level Constants (total 30)
Constants used by Dialer.
Constants used by Dialer.
Constants used by ConnUpgrader.
Constants used by ConnUpgrader.
All control frames MUST have a payload length of 125 bytes or less and MUST NOT be fragmented.
Header size length bounds in bytes.
Header size length bounds in bytes.
Operation codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-5.2
Operation codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-5.2
Operation codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-5.2
Operation codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-5.2
Operation codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-5.2
Operation codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-5.2
StateClientSide means that endpoint (caller) is a client.
StateExtended means that extension was negotiated during handshake.
StateFragmented means that endpoint (caller) has received fragmented
frame and waits for continuation parts.
StateServerSide means that endpoint (caller) is a server.
StatusAbnormalClosure is a special code designated for use in
applications.
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
StatusNoStatusRcvd is a special code designated for use in applications.
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
Status codes defined by specification.
See https://tools.ietf.org/html/rfc6455#section-7.4.1
![]() |
The pages are generated with Golds v0.8.2. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |