Documentation
¶
Overview ¶
Package socketio is a Go port of the Node.js Socket.IO server. It implements the Engine.IO v4 transport layer (HTTP long-polling and WebSocket, with the polling→websocket upgrade) and the Socket.IO v5 protocol (namespaces, rooms, events, and acknowledgements), exposing an API that mirrors socket.io:
io := socketio.New()
io.OnConnection(func(s *socketio.Socket) {
s.On("chat", func(args []any) []any {
io.To("room1").Emit("chat", args...)
return nil
})
s.Join("room1")
})
http.Handle("/socket.io/", io)
http.ListenAndServe(":3000", nil)
Index ¶
- Constants
- Variables
- func Reconstruct(data any, buffers [][]byte) any
- type Adapter
- type BroadcastOperator
- func (b *BroadcastOperator) Compress(on bool) *BroadcastOperator
- func (b *BroadcastOperator) Emit(event string, args ...any)
- func (b *BroadcastOperator) Except(socketID string) *BroadcastOperator
- func (b *BroadcastOperator) In(room string) *BroadcastOperator
- func (b *BroadcastOperator) To(room string) *BroadcastOperator
- func (b *BroadcastOperator) Volatile() *BroadcastOperator
- type BroadcastTarget
- type Broadcaster
- type Emitter
- type EventHandler
- type Namespace
- func (ns *Namespace) DisconnectSockets(closeTransport bool)
- func (ns *Namespace) Emit(event string, args ...any)
- func (ns *Namespace) FetchSockets() []*Socket
- func (ns *Namespace) Name() string
- func (ns *Namespace) OnConnection(fn func(*Socket)) *Namespace
- func (ns *Namespace) SetAdapter(a Adapter) *Namespace
- func (ns *Namespace) Sockets() []*Socket
- func (ns *Namespace) SocketsInRoom(room string) []*Socket
- func (ns *Namespace) SocketsJoin(rooms ...string)
- func (ns *Namespace) SocketsLeave(rooms ...string)
- func (ns *Namespace) To(room string) *BroadcastOperator
- func (ns *Namespace) Use(fn func(socket *Socket, next func(err error))) *Namespace
- type Options
- type Packet
- type PacketType
- type RoomTargeter
- type Server
- func (s *Server) Attach(mux *http.ServeMux)
- func (s *Server) Close()
- func (s *Server) DisconnectSockets(closeTransport bool)
- func (s *Server) Emit(event string, args ...any)
- func (s *Server) FetchSockets() []*Socket
- func (s *Server) Handler(next http.Handler) http.Handler
- func (s *Server) Of(name string) *Namespace
- func (s *Server) OnConnection(fn func(*Socket))
- func (s *Server) OnServerEvent(event string, handler func(args []any)) *Server
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) ServerSideEmit(event string, args ...any)
- func (s *Server) SetBroadcaster(b Broadcaster) *Server
- func (s *Server) Sockets() []*Socket
- func (s *Server) SocketsJoin(rooms ...string)
- func (s *Server) SocketsLeave(rooms ...string)
- func (s *Server) To(room string) *BroadcastOperator
- func (s *Server) Use(fn func(socket *Socket, next func(err error))) *Server
- type Socket
- func (s *Socket) Auth() any
- func (s *Socket) Broadcast() *BroadcastOperator
- func (s *Socket) Data() map[string]any
- func (s *Socket) Delete(key string) *Socket
- func (s *Socket) Disconnect(closeTransport bool)
- func (s *Socket) Emit(event string, args ...any) error
- func (s *Socket) EmitAck(event string, timeout time.Duration, args ...any) ([]any, error)
- func (s *Socket) EmitWithAck(event string, ackFn func(args []any), args ...any) error
- func (s *Socket) Get(key string) (any, bool)
- func (s *Socket) GetString(key string) string
- func (s *Socket) ID() string
- func (s *Socket) Join(rooms ...string) *Socket
- func (s *Socket) Leave(rooms ...string) *Socket
- func (s *Socket) Namespace() *Namespace
- func (s *Socket) Off(event string) *Socket
- func (s *Socket) On(event string, handler EventHandler) *Socket
- func (s *Socket) OnDisconnect(fn func(reason string)) *Socket
- func (s *Socket) Rooms() []string
- func (s *Socket) Set(key string, value any) *Socket
- func (s *Socket) To(room string) *BroadcastOperator
Constants ¶
const DefaultPath = "/socket.io/"
DefaultPath is the HTTP path Socket.IO serves from.
const ProtocolVersion = 5
ProtocolVersion is the Socket.IO protocol revision implemented here (v5, which rides on Engine.IO v4).
Variables ¶
var ErrInvalidPacket = errors.New("socketio: invalid packet")
ErrInvalidPacket indicates a malformed Socket.IO packet.
Functions ¶
func Reconstruct ¶
Reconstruct walks a payload replacing {"_placeholder":true,"num":N} markers with the matching binary buffer. It is exported for client implementations that reassemble incoming binary packets.
Types ¶
type Adapter ¶
type Adapter interface {
// Add registers a socket in the namespace.
Add(socketID string, s *Socket)
// Remove deletes a socket and drops it from every room.
Remove(socketID string)
// Join adds a socket to a room.
Join(socketID, room string)
// Leave removes a socket from a room.
Leave(socketID, room string)
// SocketsInRoom returns the sockets that are members of a room.
SocketsInRoom(room string) []*Socket
// AllSockets returns every socket in the namespace.
AllSockets() []*Socket
// Get returns a socket by id.
Get(socketID string) (*Socket, bool)
}
Adapter stores which sockets belong to a namespace and its rooms. The default implementation keeps everything in process; supplying a custom Adapter (e.g. backed by Redis) is the extension point for scaling a namespace across multiple server instances.
type BroadcastOperator ¶
type BroadcastOperator struct {
// contains filtered or unexported fields
}
BroadcastOperator emits events to a filtered set of sockets in a namespace — optionally scoped to one or more rooms and excluding specific sockets. It is returned by Namespace.To, Server.To, and Socket.To, and is the equivalent of io.to(room).emit(...).
func (*BroadcastOperator) Compress ¶
func (b *BroadcastOperator) Compress(on bool) *BroadcastOperator
Compress sets whether the payload should be compressed by the transport. It is advisory in this implementation.
func (*BroadcastOperator) Emit ¶
func (b *BroadcastOperator) Emit(event string, args ...any)
Emit sends an event to every socket matched by the operator. When a cluster Broadcaster is installed, the broadcast is published to all nodes (which each deliver it to their local sockets); otherwise it is delivered locally.
func (*BroadcastOperator) Except ¶
func (b *BroadcastOperator) Except(socketID string) *BroadcastOperator
Except excludes a socket id from the broadcast.
func (*BroadcastOperator) In ¶
func (b *BroadcastOperator) In(room string) *BroadcastOperator
In is an alias for To, matching socket.io's io.in(room).
func (*BroadcastOperator) To ¶
func (b *BroadcastOperator) To(room string) *BroadcastOperator
To narrows the broadcast to an additional room.
func (*BroadcastOperator) Volatile ¶
func (b *BroadcastOperator) Volatile() *BroadcastOperator
Volatile marks the broadcast as volatile: messages that cannot be delivered immediately (e.g. to a client mid-reconnect) may be dropped. On this single-node, buffered implementation it is advisory.
type BroadcastTarget ¶
type BroadcastTarget interface {
Emitter
RoomTargeter
}
BroadcastTarget is the combination satisfied by the room-addressable emitters (server, namespace, and broadcast operator): they can both narrow to a room and emit to the resulting set.
type Broadcaster ¶
type Broadcaster interface {
// Publish sends a serialized broadcast to all instances (including this
// one — pub/sub echoes to the publisher).
Publish(data []byte) error
// OnMessage registers the handler invoked for every received broadcast.
OnMessage(func(data []byte))
// Close shuts the broadcaster down.
Close() error
}
Broadcaster fans broadcasts out to other server instances. Installing one (Server.SetBroadcaster) turns a single-node server into a cluster member: a broadcast is published once and each node delivers it to its own local sockets. The reference implementation is the Redis adapter in the redis subpackage, but any pub/sub transport can implement this interface.
type Emitter ¶
Emitter is anything that can broadcast an event to a set of sockets without a per-socket error — the server, a namespace, and a broadcast operator all fan an event out to many recipients, so a delivery error to any single socket is not surfaced. (Socket.Emit, which targets one client, deliberately returns an error and is therefore not an Emitter.)
type EventHandler ¶
EventHandler handles an inbound event. It receives the event arguments and may return a non-nil slice to acknowledge the event (sent back to the client when the event requested an ack).
type Namespace ¶
type Namespace struct {
// contains filtered or unexported fields
}
Namespace is a communication channel that partitions a Socket.IO server. Each namespace has its own set of connected sockets, rooms, and connection handlers. The default namespace is "/".
func (*Namespace) DisconnectSockets ¶
DisconnectSockets disconnects every socket in the namespace.
func (*Namespace) FetchSockets ¶
FetchSockets returns all sockets in the namespace (alias for Sockets, matching io.fetchSockets()).
func (*Namespace) OnConnection ¶
OnConnection registers a handler invoked for each new socket that connects to this namespace.
func (*Namespace) SetAdapter ¶
SetAdapter replaces the namespace's room adapter (e.g. with a Redis-backed one for multi-node scale-out). Call it before any sockets connect.
func (*Namespace) SocketsInRoom ¶
SocketsInRoom returns the sockets that are members of a room.
func (*Namespace) SocketsJoin ¶
SocketsJoin makes every socket in the namespace join the given rooms.
func (*Namespace) SocketsLeave ¶
SocketsLeave makes every socket in the namespace leave the given rooms.
func (*Namespace) To ¶
func (ns *Namespace) To(room string) *BroadcastOperator
To returns a broadcast operator scoped to a room within this namespace.
func (*Namespace) Use ¶
Use registers connection middleware for the namespace. Each middleware runs for every incoming connection before the connection handler; calling next with a non-nil error rejects the connection with a CONNECT_ERROR carrying the error's message — the equivalent of io.use((socket, next) => ...).
type Options ¶
type Options struct {
// Path is the HTTP path the server handles (default "/socket.io/").
Path string
// PingInterval is how often the server sends heartbeat pings.
PingInterval time.Duration
// PingTimeout is how long the server waits for a pong before disconnecting.
PingTimeout time.Duration
// MaxPayload advertises the maximum HTTP payload size to clients.
MaxPayload int
// CheckOrigin, if set, authorizes cross-origin requests. When nil, all
// origins are allowed.
CheckOrigin func(r *http.Request) bool
}
Options configures a Server.
type Packet ¶
type Packet struct {
Type PacketType
Namespace string // defaults to "/"
ID *uint64
// Data is the decoded JSON payload: an array for Event/Ack ([name, args...]
// or [args...]) and an object for Connect/ConnectError.
Data any
// contains filtered or unexported fields
}
Packet is a decoded Socket.IO protocol packet.
func DecodePacket ¶
DecodePacket parses a Socket.IO packet from its wire form.
func (Packet) Args ¶
Args returns the event arguments (everything after the event name) for an Event packet, or the full array for an Ack packet.
func (Packet) Attachments ¶
Attachments returns the declared number of binary attachments for a BINARY_EVENT/BINARY_ACK packet.
func (Packet) Encode ¶
Encode renders a packet to its Socket.IO wire form (the string carried inside an Engine.IO MESSAGE packet).
func (Packet) EncodeBinary ¶
EncodeBinary encodes a packet, extracting any binary attachments. When the payload contains []byte values the packet type is promoted to its binary variant and the buffers are returned separately; otherwise buffers is nil. It is exported for client implementations.
type PacketType ¶
type PacketType byte
PacketType identifies a Socket.IO packet.
const ( // Connect initiates a namespace connection. Connect PacketType = iota // Disconnect leaves a namespace. Disconnect // Event carries an application event and its arguments. Event // Ack answers an Event that requested acknowledgement. Ack // ConnectError reports a failed namespace connection. ConnectError // BinaryEvent is an Event with binary attachments (decoded as text here). BinaryEvent // BinaryAck is an Ack with binary attachments (decoded as text here). BinaryAck )
func (PacketType) String ¶
func (t PacketType) String() string
type RoomTargeter ¶
type RoomTargeter interface {
To(room string) *BroadcastOperator
}
RoomTargeter is anything that can scope a broadcast to a room, returning a *BroadcastOperator for further chaining (.To/.Except/.Emit). The server, a namespace, an individual socket, and an existing operator all expose this, mirroring socket.io's io.to(room) / socket.to(room) API.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a Socket.IO server. It implements http.Handler and should be mounted at its configured Path.
func (*Server) Close ¶
func (s *Server) Close()
Close disconnects every connected session and shuts the server down. It does not stop the underlying http.Server (the caller owns that).
func (*Server) DisconnectSockets ¶
DisconnectSockets disconnects every socket in the default namespace.
func (*Server) FetchSockets ¶
FetchSockets returns all sockets in the default namespace.
func (*Server) Handler ¶
Handler wraps the server so it intercepts Socket.IO requests (those under its Path) and delegates everything else to next — the Go equivalent of attaching Socket.IO to an existing HTTP server that is otherwise served by Express:
app := express.New() // your routes
io := socketio.New() // your socket handlers
http.ListenAndServe(":3000", io.Handler(app))
next may be any http.Handler (an *express.Application, an http.ServeMux, ...); pass nil to 404 non-Socket.IO requests.
func (*Server) Of ¶
Of returns the namespace with the given name, creating it if necessary. A name without a leading slash has one added.
func (*Server) OnConnection ¶
OnConnection registers a handler invoked when a socket connects to the default namespace. It is the equivalent of io.on("connection", ...).
func (*Server) OnServerEvent ¶
OnServerEvent registers a handler for server-side events delivered via ServerSideEmit. On this single-node implementation these are local; a multi-node deployment would relay them between servers through an adapter.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler and dispatches Engine.IO transport requests.
func (*Server) ServerSideEmit ¶
ServerSideEmit emits an event to other servers (and this one), the equivalent of io.serverSideEmit. Single-node: it invokes locally registered handlers.
func (*Server) SetBroadcaster ¶
func (s *Server) SetBroadcaster(b Broadcaster) *Server
SetBroadcaster installs a cluster broadcaster. Once set, every room/namespace broadcast is published through it and delivered to local sockets when the message is received back, so all nodes in the cluster stay in sync.
func (*Server) SocketsJoin ¶
SocketsJoin makes every socket in the default namespace join the given rooms.
func (*Server) SocketsLeave ¶
SocketsLeave makes every socket in the default namespace leave the given rooms.
func (*Server) To ¶
func (s *Server) To(room string) *BroadcastOperator
To returns a broadcast operator scoped to a room in the default namespace.
type Socket ¶
type Socket struct {
// contains filtered or unexported fields
}
Socket is a single client connection to a namespace. It is the primary object applications interact with — registering event handlers, emitting events, and joining rooms.
func (*Socket) Broadcast ¶
func (s *Socket) Broadcast() *BroadcastOperator
Broadcast returns an operator targeting every other socket in the namespace.
func (*Socket) Disconnect ¶
Disconnect closes the socket, optionally closing the underlying transport.
func (*Socket) EmitAck ¶
EmitAck sends an event and blocks until the client acknowledges it or timeout elapses, returning the acknowledgement arguments.
func (*Socket) EmitWithAck ¶
EmitWithAck sends an event and invokes ackFn with the client's acknowledgement arguments.
func (*Socket) GetString ¶
GetString returns a stored string value, or "" if missing / not a string.
func (*Socket) On ¶
func (s *Socket) On(event string, handler EventHandler) *Socket
On registers a handler for an event.
func (*Socket) OnDisconnect ¶
OnDisconnect registers a callback invoked when the socket disconnects.
func (*Socket) Set ¶
Set stores an arbitrary value on the socket, persisting for the lifetime of the connection — the equivalent of Socket.IO's socket.data. Use it to attach session-like state (the authenticated user, a tenant id, ...).
func (*Socket) To ¶
func (s *Socket) To(room string) *BroadcastOperator
To returns a broadcast operator that targets a room, excluding this socket — the equivalent of socket.to(room).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client is a Go Socket.IO client.
|
Package client is a Go Socket.IO client. |
|
docs
|
|
|
gen
command
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser).
|
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser). |
|
Package engineio implements the Engine.IO v4 protocol codec — the transport framing layer that Socket.IO is built on.
|
Package engineio implements the Engine.IO v4 protocol codec — the transport framing layer that Socket.IO is built on. |
|
examples
|
|
|
chat
command
Command chat is a small Socket.IO server in Go: it echoes messages and broadcasts chat messages to everyone in a room.
|
Command chat is a small Socket.IO server in Go: it echoes messages and broadcasts chat messages to everyone in a room. |
|
client
command
Command client connects to a Socket.IO server using the Go client and exchanges a couple of events.
|
Command client connects to a Socket.IO server using the Go client and exchanges a couple of events. |
|
internal
|
|
|
ws
Package ws is a minimal, dependency-free RFC 6455 WebSocket server implementation, sufficient to carry Engine.IO/Socket.IO traffic.
|
Package ws is a minimal, dependency-free RFC 6455 WebSocket server implementation, sufficient to carry Engine.IO/Socket.IO traffic. |
|
Package redis provides a Redis-backed Broadcaster for socketio, enabling multi-node scale-out: broadcasts are relayed between server instances over Redis pub/sub so a message emitted on one node reaches sockets connected to any node.
|
Package redis provides a Redis-backed Broadcaster for socketio, enabling multi-node scale-out: broadcasts are relayed between server instances over Redis pub/sub so a message emitted on one node reaches sockets connected to any node. |