Documentation
¶
Overview ¶
Package websocket implements the WebSocket protocol (RFC 6455) on top of fasthttp.
Servers call Accept from a fasthttp request handler; applications served through fasthttpadaptor call it from a fasthttp handler, not from the adapted net/http one. Clients call Dial.
Conn methods take a context for cancellation and deadlines. A read or write that is cancelled or times out closes the connection, since the frame stream cannot be resumed. One that gives up before its operation starts, while waiting for another call, leaves it open; a read with a Pong to send and a Conn.Writer with part of its message sent have started. ReadTimeout and WriteTimeout in the options bound each read and frame write without wrapping each context; see AcceptOptions.
Once a connection is closed, reads and writes return the error that closed it. A closing handshake, a protocol violation by the peer or a transport that failed without a Close frame yield a CloseError value, the last with StatusAbnormalClosure: inspect it with CloseStatus, or with
var ce CloseError
if errors.As(err, &ce) { ... }
A cancelled or expired context yields its error; ReadTimeout and WriteTimeout yield a timeout error; closing with Conn.CloseNow, or writing after the Close frame has been sent, yields net.ErrClosed.
Compression with permessage-deflate (RFC 7692) is off unless CompressionMode in the options enables it; MaxMessageSize then bounds messages before and after decompression.
Index ¶
- Constants
- func Accept(ctx *fasthttp.RequestCtx, opts *AcceptOptions, handler func(*Conn)) error
- type AcceptOptions
- type CloseError
- type CompressionMode
- type Conn
- func (c *Conn) Close(ctx context.Context, code StatusCode, reason string) error
- func (c *Conn) CloseNow() error
- func (c *Conn) CloseRead(ctx context.Context)
- func (c *Conn) Context() context.Context
- func (c *Conn) Ping(ctx context.Context) error
- func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)
- func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error)
- func (c *Conn) Subprotocol() string
- func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error
- func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error)
- type DialOptions
- type MessageType
- type StatusCode
Examples ¶
Constants ¶
const DefaultMaxMessageSize = 4 << 20
DefaultMaxMessageSize is the message size limit used when MaxMessageSize is zero.
Variables ¶
This section is empty.
Functions ¶
func Accept ¶
func Accept(ctx *fasthttp.RequestCtx, opts *AcceptOptions, handler func(*Conn)) error
Accept upgrades the request to a WebSocket connection and arranges for handler to run on it once the request handler returns. The connection is closed when handler returns; calls still in flight on other goroutines fail. Headers set on ctx.Response before the call are sent with the 101 response, except those of the handshake itself and Trailer, which Accept removes or replaces; one stored under a spelling it cannot remove is a server error.
If the request is not a valid WebSocket handshake, Accept writes an error response and returns the reason; the caller should then return without touching the response.
fasthttp skips the upgrade while shutting down with fasthttp.Server.CloseOnShutdown. The Server's timeouts and Shutdown do not apply to the upgraded connection; use the options here instead. The connection's TCP or Unix socket is closed with the WebSocket connection. A connection that hides its socket, as with fasthttp.Server.MaxConnsPerIP without TLS or a net.Conn of the caller's, is closed by fasthttp when handler returns, or with the WebSocket connection under fasthttp.Server.KeepHijackedConns.
Example ¶
package main
import (
"log"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/websocket"
)
func main() {
handler := func(ctx *fasthttp.RequestCtx) {
err := websocket.Accept(ctx, nil, func(c *websocket.Conn) {
for {
typ, msg, err := c.Read(c.Context())
if err != nil {
return
}
if err := c.Write(c.Context(), typ, msg); err != nil {
return
}
}
})
if err != nil {
log.Printf("websocket: %v", err)
}
}
log.Fatal(fasthttp.ListenAndServe(":8080", handler))
}
Output:
Types ¶
type AcceptOptions ¶
type AcceptOptions struct {
// CheckOrigin reports whether the request's Origin is acceptable. When
// nil, requests without an Origin header are accepted and all others must
// carry exactly one Origin of the form scheme://host[:port] whose host and
// port equal the request Host, compared case-insensitively and without
// regard to the scheme.
CheckOrigin func(ctx *fasthttp.RequestCtx) bool
// Subprotocols lists the supported subprotocols in order of preference.
// The first one the client also offers is selected; with no match none is.
// Names must be distinct HTTP tokens.
Subprotocols []string
// MaxMessageSize limits the size of a message, counting all its fragments.
// A larger message closes the connection with [StatusMessageTooBig].
// Zero means [DefaultMaxMessageSize].
MaxMessageSize int
// ReadTimeout bounds every [Conn.Read], [Conn.Reader] and reader Read
// call, but not [Conn.CloseRead]; WriteTimeout bounds every frame write,
// but not the wait of [Conn.Ping] for the pong. A call that exceeds its
// bound once its operation has started closes the connection: a read with
// a Pong to send and a [Conn.Writer] with part of its message sent have.
// One that times out before that, while waiting for another call, returns
// [os.ErrDeadlineExceeded] and leaves it open. Zero means no bound.
ReadTimeout time.Duration
WriteTimeout time.Duration
// CompressionMode enables permessage-deflate when the client offers it.
// Zero means [CompressionDisabled].
CompressionMode CompressionMode
// CompressionThreshold is the size from which a message is compressed; a
// [Conn.Writer] message is judged by its first fragment. Zero means 128
// bytes with context takeover and 512 without.
CompressionThreshold int
}
AcceptOptions configures Accept. The zero value is valid.
type CloseError ¶
type CloseError struct {
Reason string
Code StatusCode
}
CloseError is the error of a connection closed with a status code.
func (CloseError) Error ¶
func (e CloseError) Error() string
Error returns the status code and reason.
type CompressionMode ¶
type CompressionMode int
CompressionMode selects how permessage-deflate (RFC 7692) is used.
const ( // CompressionDisabled neither offers nor accepts compression. CompressionDisabled CompressionMode = iota // CompressionNoContextTakeover compresses each message on its own, with // compressors and decompressors taken from pools, so a connection holds // no compression state between messages. Small messages gain little. CompressionNoContextTakeover // CompressionContextTakeover lets messages refer back to earlier ones, // which compresses streams of similar small messages well. A connection // keeps the last 4 KiB it compressed and the last 32 KiB it decompressed // as dictionaries, in buffers of twice that size; the compressors // themselves stay pooled. The peer may still decline context takeover for // either direction. CompressionContextTakeover )
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a WebSocket connection.
Read, Reader and CloseRead must not be called concurrently with each other, and a reader from Reader or a writer from Writer is not safe for concurrent use; all other methods may be called concurrently. See the package documentation for the errors a closed connection reports.
func Dial ¶
Dial connects to the WebSocket server at u, a ws or wss URL (http and https are accepted as aliases) without a fragment, and completes the handshake. ctx bounds the whole of it, apart from a custom DialOptions.Dial. The path is sent as given; user information in the URL becomes a Basic Authorization header unless DialOptions.Header carries one. Redirects are not followed. Interim 1xx responses are skipped; a final response other than 101 is an error, and its status and headers are available through DialOptions.Response.
Example ¶
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/valyala/fasthttp/websocket"
)
func main() {
ctx := context.Background()
opts := &websocket.DialOptions{ReadTimeout: time.Minute, WriteTimeout: 10 * time.Second}
c, err := websocket.Dial(ctx, "wss://example.com/echo", opts)
if err != nil {
log.Println(err)
return
}
defer c.Close(ctx, websocket.StatusNormalClosure, "")
if err := c.Write(ctx, websocket.MessageText, []byte("hello")); err != nil {
log.Println(err)
return
}
_, msg, err := c.Read(ctx)
if err != nil {
log.Println(err)
return
}
fmt.Printf("%s\n", msg)
}
Output:
func (*Conn) Close ¶
Close performs the closing handshake: it sends a Close frame carrying code and reason, waits for the peer's Close frame and closes the connection. The wait ends at the ctx deadline; without one it lasts at most ReadTimeout, or five seconds when that is zero too. Close returns an error only for an invalid code or reason, or when the Close frame could not be sent and the connection is still usable. Otherwise it returns nil once the connection is closed, whether or not the peer answered; context.Cause(c.Context()) tells why.
func (*Conn) CloseRead ¶
CloseRead starts a goroutine that reads and handles control frames, so a connection used only for writing still answers pings and sees the peer's Close frame. It runs until the connection is closed, which cancelling ctx does; ReadTimeout does not apply to it. A data message closes the connection with StatusPolicyViolation. Conn.Read and Conn.Reader must not be called afterwards; use Conn.Context to learn when the connection is closed.
func (*Conn) Context ¶
Context returns a context that is cancelled when the connection is closed. context.Cause reports the error that closed it.
func (*Conn) Ping ¶
Ping sends a ping and waits for the matching pong. Pongs are only seen while another goroutine is in Conn.Read or Conn.Reader, or after Conn.CloseRead. Only one Ping is in flight at a time.
func (*Conn) Read ¶
Read reads one message. The returned bytes are owned by the connection and stay valid until the next Read or Conn.Reader call.
func (*Conn) Reader ¶
Reader returns a reader for the next message, whose Read calls are bounded by ctx as well. It is valid until the next Conn.Read or Reader call, which discards whatever is left of the message; it must not be used afterwards.
func (*Conn) Subprotocol ¶
Subprotocol returns the negotiated subprotocol, or "" if none was.
func (*Conn) Write ¶
Write sends p as a single-frame message of type typ. The wait for another writer can end through ctx or WriteTimeout without closing the connection.
func (*Conn) Writer ¶
func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error)
Writer returns a writer for one message of type typ; ctx also bounds the frames its Write and Close calls send. Data is buffered and sent in fragments; a write larger than the buffer goes out as a fragment of its own, and Close sends what is left as the last one. Only one writer is open at a time: Conn.Write and further Writer calls block until it is closed, which a failed write also does.
type DialOptions ¶
type DialOptions struct {
// Dial establishes the TCP connection. nil means [net.Dialer], which
// honors ctx; a custom dialer is bounded only by its own timeouts. The
// dialers of the fasthttpproxy package can be used directly.
Dial fasthttp.DialFunc
// TLSConfig is used for wss URLs. nil means the default configuration.
// ServerName is taken from the URL when empty.
TLSConfig *tls.Config
// Header holds extra request headers. A Host header overrides the URL
// host; the headers of the handshake itself (Connection, Upgrade,
// Sec-WebSocket-*, Content-Length, Transfer-Encoding, Trailer) are
// rejected.
Header *fasthttp.RequestHeader
// Response, when not nil, receives the status and headers of the
// handshake response, also when the handshake fails.
Response *fasthttp.Response
// Subprotocols lists the subprotocols to offer, in order of preference.
// Names must be distinct HTTP tokens.
Subprotocols []string
// ReadBufferSize is the size of the buffer the handshake response and
// then the frames are read through; the response headers must fit in it.
// Zero means 4096.
ReadBufferSize int
// MaxMessageSize, ReadTimeout, WriteTimeout, CompressionMode and
// CompressionThreshold work as in [AcceptOptions].
MaxMessageSize int
ReadTimeout time.Duration
WriteTimeout time.Duration
CompressionMode CompressionMode
CompressionThreshold int
}
DialOptions configures Dial. The zero value is valid.
type MessageType ¶
type MessageType int
MessageType is the type of a data message.
const ( MessageText MessageType = 1 MessageBinary MessageType = 2 )
Data message types. A text message must be valid UTF-8; received ones are checked, sent ones are not.
type StatusCode ¶
type StatusCode int
StatusCode is a close status code (RFC 6455 section 7.4).
const ( StatusNormalClosure StatusCode = 1000 StatusGoingAway StatusCode = 1001 StatusProtocolError StatusCode = 1002 StatusUnsupportedData StatusCode = 1003 StatusNoStatusReceived StatusCode = 1005 StatusAbnormalClosure StatusCode = 1006 StatusInvalidFramePayloadData StatusCode = 1007 StatusPolicyViolation StatusCode = 1008 StatusMessageTooBig StatusCode = 1009 StatusMandatoryExtension StatusCode = 1010 StatusInternalError StatusCode = 1011 StatusServiceRestart StatusCode = 1012 StatusTryAgainLater StatusCode = 1013 StatusBadGateway StatusCode = 1014 StatusTLSHandshake StatusCode = 1015 )
Close status codes. StatusNoStatusReceived, StatusAbnormalClosure and StatusTLSHandshake never appear in a Close frame and Conn.Close rejects them; the first two are reported for a Close frame without a status and for a connection that ended without a Close frame.
func CloseStatus ¶
func CloseStatus(err error) StatusCode
CloseStatus returns the status code of the CloseError err is or wraps, or -1 if there is none.