transport

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package transport implements the Engine.IO v4 protocol primitives (packet/payload encoding) and the underlying HTTP long-polling and WebSocket transports.

Protocol reference: https://socket.io/docs/v4/engine-io-protocol/

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRequestOverlap    = errors.New("engineio: request overlap from client")
	ErrDataRequestActive = errors.New("engineio: data request overlap from client")
	ErrPollClosed        = errors.New("engineio: poll connection closed prematurely")
	ErrWriteError        = errors.New("engineio: write error")
	ErrUpgradeTimeout    = errors.New("engineio: upgrade timeout")
	ErrUpgradeAborted    = errors.New("engineio: client did not complete upgrade")
)

Sentinel errors surfaced to the session socket.

View Source
var ErrInvalidPacket = errors.New("engineio: invalid packet")

ErrInvalidPacket is returned when a packet cannot be decoded.

View Source
var ErrInvalidPayload = errors.New("engineio: invalid payload")

ErrInvalidPayload is returned when a polling payload cannot be decoded.

View Source
var ErrPayloadTooLarge = errors.New("engineio: payload too large")

ErrPayloadTooLarge is returned when a single packet within a polling payload exceeds the configured maxPayload. It is treated as fatal: the caller closes the connection (the payload cannot be partially honored).

Functions

func EncodePacket

func EncodePacket(p *Packet, supportsBinary bool) []byte

EncodePacket serializes a packet.

When the packet carries binary data and supportsBinary is true, the raw bytes are returned unchanged (the packet type is implicitly "message", which matches the WebSocket transport). Otherwise binary data is base64-encoded and prefixed with a 'b' character, as required by the HTTP long-polling transport.

func EncodePayload

func EncodePayload(pkts []*Packet) []byte

EncodePayload serializes a batch of packets into a polling payload. Binary packets are always base64-encoded, as required by the protocol.

func SetLogger added in v1.1.0

func SetLogger(l Logger)

SetLogger sets the package-level logger used for payload-truncation warnings. A nil logger leaves the current logger in place.

Types

type HTTPServing

type HTTPServing interface {
	ServeHTTP(w http.ResponseWriter, r *http.Request)
}

HTTPServing is implemented by transports that accept plain HTTP requests (the HTTP long-polling transport).

type Handler

type Handler interface {
	// OnPacket is called for every packet received from the transport.
	OnPacket(p *Packet)
	// OnError is called when the transport encounters a non-fatal error.
	OnError(err error)
	// OnClose is called when the transport has been closed.
	OnClose()
	// OnDrain is called once all packets handed to Send have been flushed
	// to the wire.
	OnDrain()
	// OnReady is called when the transport becomes writable again, giving
	// the socket a chance to flush buffered packets.
	OnReady()
}

Handler receives events from a Transport. It is implemented by the Engine.IO session socket.

type Logger

type Logger interface {
	Debugf(format string, args ...any)
	Warnf(format string, args ...any)
}

Logger is the minimal logging interface used by transports.

type Packet

type Packet struct {
	// Type is the packet type. A packet decoded from a binary source always
	// has Type == Message.
	Type Type
	// Data is the packet payload. For a text packet it holds the raw UTF-8
	// data. For a binary packet it holds the binary payload.
	Data []byte
	// IsBinary reports whether Data holds binary data. When true the packet
	// is a message packet carrying binary data.
	IsBinary bool
}

Packet is a single Engine.IO packet.

func DecodePacket

func DecodePacket(b []byte, isBinary bool) (Packet, error)

DecodePacket parses a single packet.

isBinary indicates the input arrived as a binary frame (e.g. a binary WebSocket frame); such a frame is always a message packet carrying binary data. Text input may be:

"<type><data>"          plain text packet
"b<base64>"             binary message payload (base64 encoded)

func DecodePayload

func DecodePayload(b []byte) ([]*Packet, error)

DecodePayload parses a polling payload into its packets. The input must be plain text (the v4 protocol never sends raw binary in polling payloads).

func DecodePayloadWithLimit added in v1.1.0

func DecodePayloadWithLimit(b []byte, maxPayload int64) ([]*Packet, error)

DecodePayloadWithLimit parses a polling payload into its packets while enforcing a maximum size. A maxPayload <= 0 disables the limit entirely.

A single packet whose own encoded size exceeds maxPayload is fatal and returns an error wrapping ErrPayloadTooLarge; the caller must close the connection. When the cumulative size of the packets decoded so far would exceed maxPayload, the remaining tail packets (the newest) are dropped with a warning instead — the payload is recoverable and the connection stays open.

type Polling

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

Polling is the HTTP long-polling transport.

It follows the semantics of the reference implementation:

  • a single pending GET request receives buffered packets (long-polling);
  • a single POST request delivers a payload from the client;
  • the transport is "writable" only while a GET request is pending;
  • an orderly close is deferred until the next poll so a `close` packet can be delivered to the client.

func NewPolling

func NewPolling() *Polling

NewPolling creates a polling transport. The default maximum accepted request body size is 1 MiB.

func (*Polling) Close

func (p *Polling) Close()

Close initiates an orderly close. If a poll request is pending, a `close` packet is delivered immediately; otherwise the close is deferred until the next poll or a 30s timeout. Discarded transports are closed without delivering any further packet.

func (*Polling) Discard

func (p *Polling) Discard()

Discard marks the transport as discarded, so Close will not attempt to deliver a close packet.

func (*Polling) DrainBuffered

func (p *Polling) DrainBuffered() []*Packet

DrainBuffered returns and clears the packets buffered while no poll request was pending. It is used during a transport upgrade so that replies that were produced before the switch are delivered over the new transport instead of being dropped when the old one is discarded.

func (*Polling) Name

func (p *Polling) Name() string

func (*Polling) Send

func (p *Polling) Send(pkts []*Packet)

Send delivers a batch of packets through the currently pending poll request, if any. The transport takes ownership of pkts.

func (*Polling) ServeHTTP

func (p *Polling) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles a single polling request.

func (*Polling) SetHandler

func (p *Polling) SetHandler(h Handler)

func (*Polling) SetLogger

func (p *Polling) SetLogger(l Logger)

SetLogger sets the logger used by the transport. It also configures the package-level logger so that payloads truncated by DecodePayloadWithLimit are logged through the transport's logger.

func (*Polling) SetMaxBufferSize

func (p *Polling) SetMaxBufferSize(n int64)

SetMaxBufferSize sets the maximum accepted POST body size. Requests larger than this are rejected with HTTP 413.

func (*Polling) SetWritable

func (p *Polling) SetWritable(v bool)

func (*Polling) Writable

func (p *Polling) Writable() bool

type Transport

type Transport interface {
	// Name returns the transport name ("polling" or "websocket").
	Name() string
	// Writable reports whether the transport is ready to accept packets.
	Writable() bool
	// SetWritable toggles the writable flag.
	SetWritable(v bool)
	// Send hands a batch of packets to the transport for delivery. The
	// transport takes ownership of the slice and delivers it in order.
	Send(pkts []*Packet)
	// Close closes the transport. Depending on the transport this may be
	// asynchronous (polling waits for the next poll to deliver a close
	// packet).
	Close()
	// Discard marks the transport as discarded; it will be closed without
	// flushing any remaining data.
	Discard()
	// SetHandler attaches the event handler and starts delivering events.
	SetHandler(h Handler)
}

Transport is a full-duplex Engine.IO transport (polling or websocket).

type Type

type Type byte

Type is the Engine.IO packet type.

const (
	Open    Type = '0'
	Close   Type = '1'
	Ping    Type = '2'
	Pong    Type = '3'
	Message Type = '4'
	Upgrade Type = '5'
	Noop    Type = '6'
)

Engine.IO packet types.

func (Type) String

func (t Type) String() string

String returns the packet type name.

type Websocket

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

Websocket is the WebSocket transport. Each Engine.IO packet is carried in its own WebSocket frame: plain text packets use text frames ("<type><data>") while binary message payloads use binary frames carrying the raw bytes.

func NewWebsocket

func NewWebsocket(ctx context.Context, conn *websocket.Conn) *Websocket

NewWebsocket wraps an accepted WebSocket connection.

func (*Websocket) Close

func (w *Websocket) Close()

Close closes the underlying WebSocket connection.

func (*Websocket) Discard

func (w *Websocket) Discard()

Discard marks the transport as discarded; subsequent events are ignored by the session socket.

func (*Websocket) Name

func (w *Websocket) Name() string

func (*Websocket) Send

func (w *Websocket) Send(pkts []*Packet)

Send delivers a batch of packets over the WebSocket connection.

func (*Websocket) SetHandler

func (w *Websocket) SetHandler(h Handler)

func (*Websocket) SetLogger

func (w *Websocket) SetLogger(l Logger)

SetLogger sets the logger used by the transport.

func (*Websocket) SetWritable

func (w *Websocket) SetWritable(v bool)

func (*Websocket) Writable

func (w *Websocket) Writable() bool

Jump to

Keyboard shortcuts

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