Documentation
¶
Overview ¶
Package gozmq is a pure-Go implementation of the ZeroMQ messaging patterns and the ZMTP 3.1 wire protocol. It has no CGO dependency and builds cleanly with CGO_ENABLED=0 on every platform the Go toolchain supports.
Overview ¶
gozmq provides the standard ZeroMQ socket patterns (REQ/REP, DEALER/ROUTER, PUB/SUB, XPUB/XSUB, PUSH/PULL, PAIR, STREAM) wired to the usual transports (tcp://, tcp6://, ipc://, inproc://, and the library-specific tls+tcp:// for TLS-wrapped TCP). Wire compatibility with libzmq >= 4.2 is a first-class goal: a gozmq socket interoperates bit-for-bit with libzmq over ZMTP 3.1 and negotiates down to 3.0 when the peer predates heartbeats. Peers whose advertised Socket-Type is incompatible with the local socket are rejected during the handshake before traffic phase begins.
See design.md at the repository root for architecture, protocol, security, and testing specifications. The public API is stable only after the v1.0.0 tag; until then, breaking changes are noted in CHANGELOG.md.
Hello world ¶
A minimal PAIR round-trip over inproc:
ctx := gozmq.NewContext()
defer ctx.Close()
server, _ := ctx.NewSocket(gozmq.Pair)
defer server.Close()
_ = server.Bind("inproc://hello")
client, _ := ctx.NewSocket(gozmq.Pair)
defer client.Close()
_ = client.Connect("inproc://hello")
callCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = client.SendMsg(callCtx, gozmq.NewMsgFromBytes([]byte("ping")))
msg, _ := server.RecvMsg(callCtx)
fmt.Printf("%s\n", msg.Bytes()) // "ping"
Received frames are ordinary Go memory owned by the caller; there is nothing to release ((*Msg).Release does nothing for them).
Receive buffer pool ¶
A socket created with WithRecvBufferPool(true) receives frames larger than 4 KiB into pooled buffers, which avoids a large allocation and its garbage-collection cost per frame. Those messages are lent ([Msg.Lent]), with an explicit contract: the receiver owns one reference and calls [Msg.Release] when done; the frames are valid until the last reference is released and are then reused; [Msg.Retain] adds a reference; releasing more than retained panics. Socket.SendMsg takes its own reference, so a forwarder can RecvMsg, SendMsg and Release in that order. To re-envelope a lent message, use [Msg.Derive] rather than wrapping its frames in a new message. There is no finalizer: a message dropped without Release is simply garbage collected, never recycled under a live frame.
Security ¶
The default security mechanism is NULL: no authentication, no encryption. This matches libzmq and is appropriate for trusted networks (inproc, ipc, or a private tcp segment) but NOT for untrusted or public networks. To authenticate and/or encrypt, choose one of:
- WithPlainAuth / WithPlainClient — username/password authentication. Credentials travel in cleartext unless the underlying transport is wrapped in tls+tcp://.
- WithCurveServer / WithCurveClient — CurveZMQ mutual authentication with forward-secret encryption using long-term Curve25519 keys.
For untrusted networks prefer CURVE, or layer PLAIN under tls+tcp://. As in libzmq, the server/client role comes from the option, not from which side binds: a WithPlainAuth socket is the PLAIN server even when it connects. A socket takes at most one mechanism; NewSocket rejects combinations.
Authorization can be delegated to an RFC 27 policy: install a security.ZAPHandler on the Context with WithZAPHandler and set the socket's domain with WithZAPDomain. The handler is called directly from the server side of every PLAIN and CURVE handshake, and from the accepting side of NULL handshakes on sockets that set a domain.
inproc connections are direct pipes between two sockets of one Context: no handshake runs, so there is no security mechanism and no ZAP check, as in libzmq. A socket configured with PLAIN, CURVE or WithSecurityMech therefore cannot use inproc: Bind or Connect on inproc:// returns an error wrapping ErrEndpointInvalid. A Context-level ZAP handler never sees inproc peers.
inproc ¶
inproc:// is built into the Context, not a transport: a Connect and its Bind are joined by one pipe pair, with no framing, no copy and no goroutine. As in libzmq, a Connect may come before the Bind: it waits, with no time limit, until the Bind, a Socket.Disconnect or Close. Each direction queues up to the sender's send HWM plus the receiver's recv HWM (unlimited if either is 0), both sides see each other's WithIdentity, and connecting to a bound socket of an incompatible type fails with ErrFSMViolation (reported as EventConnectFailed for a waiting Connect). Closing or disconnecting either side detaches both; messages already queued stay receivable. STREAM sockets cannot use inproc.
Defaults ¶
Sockets constructed via Context.NewSocket start with these defaults. Each is overridable via the corresponding With* option (WithSendHWM, WithRecvHWM, WithLinger, WithHeartbeat, WithHandshakeTimeout, WithMaxMessageSize, WithReconnectInterval, WithReconnectIntervalMax); see each option's documentation for the full semantics.
sendHWM 1000 (outbound high-water mark, messages) recvHWM 1000 (inbound high-water mark, messages) linger 1s (Close drain grace period) heartbeatInterval 30s (ZMTP 3.1 PING cadence) heartbeatTimeout 90s (peer-unresponsive deadline; 0 = 3× interval) handshakeTimeout 30s (greeting + security + TLS handshake cap; 0 = none) maxMessageSize 64 MiB (per-message ceiling; oversize tears session) reconnectInterval 100ms (base backoff; exponential with 20% jitter) reconnectIntervalMax 30s (backoff cap; 0 = no cap, diverges from libzmq)
These differ from libzmq where libzmq's defaults are hostile: notably, linger defaults to 1s (not infinite) so a forgotten Close cannot hang the process indefinitely.
STREAM sockets ¶
The STREAM socket type is a deliberate departure from the rest of the ZMTP patterns and is best thought of as a raw-TCP bridge dressed up as a ZeroMQ socket. Specifically, STREAM:
- carries raw bytes on the wire — there is no ZMTP frame envelope, so every byte sent or received corresponds 1:1 to TCP payload bytes;
- does NOT perform a ZMTP greeting or security handshake with the peer, so it interoperates with any TCP server or client (HTTP, line-based protocols, opaque binary streams);
- synthesises a per-connection routing identity. RecvMsg returns a two- frame message whose leading frame is the connection identity and whose second frame is the raw payload; SendMsg requires the same connection identity as the leading frame to address a specific peer (an empty payload closes that connection);
- has no subscription, topic, or pub/sub semantics — WithSubscribe and XPUB verbose-mode options do not apply;
- dials exactly once on Connect and never reconnects: a dial failure is returned synchronously (plus EventConnectFailed on the monitor channel) and a later peer disconnect is final. Reconnect supervision for raw STREAM peers is the application's responsibility; Socket.Disconnect closes the connection a Connect made;
- honours WithSendHWM and WithRecvHWM as given (0 means unlimited) and WithLinger: Close flushes queued outbound data before closing each connection;
- diverges from libzmq in NOT delivering synthetic [identity, empty] connect/disconnect notification messages (libzmq's ZMQ_STREAM_NOTIFY behavior). Use a monitor channel to observe STREAM peer lifecycle.
Options that configure ZMTP-layer behavior (security, heartbeat, identity, handshake timeout, ZAP domain) are rejected by NewSocket on STREAM sockets rather than silently ignored.
Concurrency model ¶
Socket.SendMsg and Socket.RecvMsg are safe for concurrent use across goroutines; the engine serializes them internally (REQ and REP reject a concurrent call that would break lock-step with ErrFSMViolation). However, the idiomatic usage — and the pattern the library is optimised for — is one goroutine per socket. Sharing a socket across many concurrent senders works but buys you nothing over a dedicated fan-in goroutine and makes flow-control reasoning harder.
Polling ¶
Poller multiplexes blocking readiness across many sockets, in the spirit of zmq_poll: register sockets with PollIn / PollOut interest masks, then call Poller.Poll to block until at least one is ready. Readiness is non-consuming — the caller still invokes RecvMsg/SendMsg on the returned sockets. One divergence from libzmq: PollOut reports only that at least one peer is attached to dispatch to; it does NOT account for high-water-mark pressure, so a SendMsg after a PollOut wakeup may still block if every peer pipe is full. Event loops ported from zmq_poll should pair PollOut sends with a deadline or context.
Close semantics ¶
Socket.Close blocks for up to the configured linger duration while the session writers flush any queued outbound messages to the wire. linger == 0 discards queued messages immediately; a negative linger waits indefinitely (matching libzmq) — this can deadlock Close if a peer never drains, so pair infinite linger with Socket.CloseCtx, which honors its context's cancellation as an escape hatch: when the context fires mid-drain, the drain is abandoned but teardown completes and the socket is fully closed on return. Close and CloseCtx are idempotent — repeated calls return nil.
Monitor events ¶
A channel registered via WithMonitor or Socket.Monitor receives Event values for lifecycle transitions (connect, listen, handshake, disconnect, close). Delivery is best-effort: if the channel is full the event is dropped rather than blocking the socket's hot path. Monitor channels must be buffered; 64-256 is a reasonable default for most applications.
Metrics and logging ¶
Socket.Metrics returns a point-in-time SocketMetrics snapshot (Sent/Recv/Dropped counters plus a QueueDepth gauge); poll it and publish to whatever sink you use. WithLogger injects a *slog.Logger for internal diagnostics (handshake failures, reconnect attempts, heartbeat loss). gozmq does not register expvar vars or emit OpenTelemetry spans itself.
Live Reconfiguration ¶
Most With* options are construction-time only because they shape the engine, session, or transport wiring created by Context.NewSocket. Use the dedicated live APIs for mutable behavior: Socket.Monitor, Socket.Subscribe, Socket.Unsubscribe, Socket.Disconnect, and Socket.Unbind. Disconnect tears down the connections to one Connect target and stops its reconnect loop (on inproc it also cancels a Connect still waiting for its Bind); Unbind stops one listener (matched against the resolved endpoint Bind produced) while leaving already- accepted connections alive, matching libzmq's zmq_unbind.
ROUTER identity handover ¶
When a peer attaches to a ROUTER claiming an identity that is already in use, gozmq hands the identity over: replies addressed to it go to the new peer from then on. The old connection is not closed; it stays attached until it disconnects, and messages it still sends arrive under the same identity. libzmq's default (ZMQ_ROUTER_HANDOVER=0) rejects the new peer and keeps the old pipe bound; its HANDOVER=1 terminates the old pipe. gozmq does neither exactly (see docs/COMPATIBILITY.md). Handover is the better default in practice — a client reconnecting before the server's TCP stack has noticed the old connection died would otherwise be stranded until the stale pipe times out — but it does mean two clients that pick the same WithIdentity value will silently evict each other rather than one failing loudly. Identities must be unique. Peers that advertise no identity get a synthesized 5-byte one (a zero byte, then a per-socket counter with a random start), never one that is already in use.
Subscription refcount ¶
SUB and XSUB maintain per-prefix refcounts. Calling Subscribe with the same prefix twice requires two matching Unsubscribe calls before the prefix is removed from the filter and a CANCEL is sent upstream. This matches libzmq and lets independent components on the same socket manage their own subscriptions without interfering.
Further reading ¶
See design.md at the repository root for the full architecture, protocol implementation notes, security mechanisms, transport details, and test strategy.
Index ¶
- Constants
- Variables
- func Proxy(ctx context.Context, frontend, backend, capture *Socket) error
- type Context
- type ContextOption
- type Event
- type EventType
- type Msg
- type Option
- func WithCurveClient(serverKey, publicKey, secretKey []byte) Option
- func WithCurveServer(secretKey []byte) Option
- func WithHandshakeTimeout(d time.Duration) Option
- func WithHeartbeat(interval, timeout time.Duration) Option
- func WithIdentity(id []byte) Option
- func WithLinger(d time.Duration) Option
- func WithLogger(l *slog.Logger) Option
- func WithMaxMessageSize(n int64) Option
- func WithMonitor(ch chan<- Event, mask EventType) Option
- func WithPlainAuth(fn func(user, pass string) bool) Option
- func WithPlainClient(username, password string) Option
- func WithReconnectInterval(d time.Duration) Option
- func WithReconnectIntervalMax(d time.Duration) Option
- func WithRecvBufferPool(enabled bool) Option
- func WithRecvHWM(n int) Option
- func WithRouterMandatory(enabled bool) Option
- func WithSecurityMech(...) Option
- func WithSendHWM(n int) Option
- func WithSubscribe(prefix []byte) Option
- func WithXPubVerbose(enabled bool) Option
- func WithZAPDomain(domain string) Option
- type PollEvent
- type PollEvents
- type Poller
- type Socket
- func (s *Socket) Bind(endpoint string) error
- func (s *Socket) Close() error
- func (s *Socket) CloseCtx(ctx context.Context) error
- func (s *Socket) Connect(endpoint string) error
- func (s *Socket) Disconnect(endpoint string) error
- func (s *Socket) LastEndpoint() string
- func (s *Socket) Metrics() SocketMetrics
- func (s *Socket) Monitor(ch chan<- Event, mask EventType) error
- func (s *Socket) RecvBytes(ctx context.Context) ([]byte, error)
- func (s *Socket) RecvMsg(ctx context.Context) (*Msg, error)
- func (s *Socket) SendBytes(ctx context.Context, b []byte) error
- func (s *Socket) SendMsg(ctx context.Context, m *Msg) error
- func (s *Socket) Subscribe(prefix []byte) error
- func (s *Socket) Type() SocketType
- func (s *Socket) Unbind(endpoint string) error
- func (s *Socket) Unsubscribe(prefix []byte) error
- type SocketMetrics
- type SocketType
Examples ¶
Constants ¶
const MaxHWM = 1 << 20
MaxHWM is the largest value WithSendHWM and WithRecvHWM accept. A positive HWM is the capacity of a per-peer channel allocated when the connection is made (8 bytes per slot), so a cap keeps a typo from reserving gigabytes per connection or overflowing the channel allocator. Use 0 for an unbounded queue.
Variables ¶
var ( // ErrContextClosed is returned by Context.NewSocket once the Context // has been closed. Context.Close closes every socket, so calls already // in flight on them see ErrSocketClosed (or, if they were passed // Context.Ctx, context.Canceled). Context.Close itself is idempotent // and returns nil on repeated calls. ErrContextClosed = zmqerr.ErrContextClosed // ErrSocketClosed is returned by the Socket methods that can fail // (SendMsg, RecvMsg, Bind, Connect, Unbind, Disconnect, Subscribe, // Monitor, ...) once the socket has been closed, including calls // blocked when Close runs. Close itself is idempotent and returns nil // on repeated calls, matching Context.Close. ErrSocketClosed = zmqerr.ErrSocketClosed // ErrFSMViolation is returned by socket methods called in the wrong // state for the socket pattern — e.g. REQ.Send when the socket is // awaiting a reply, REP.Recv when the socket is mid-response, a // concurrent call that would break REQ/REP lock-step, // Subscribe/Unsubscribe on a non-SUB socket, RecvBytes on a multipart // message, or SendMsg with a nil message. ErrFSMViolation = zmqerr.ErrFSMViolation // ErrHandshakeTimeout is returned (or surfaced on a monitor channel // as EventHandshakeFailedProtocol) when the ZMTP greeting plus // security handshake does not complete within the duration configured // by [WithHandshakeTimeout]. On client sockets the reconnector then // backs off and retries. ErrHandshakeTimeout = zmqerr.ErrHandshakeTimeout // ErrAuthFailed is reported when the security mechanism rejects a // peer — PLAIN credentials refused by the server's validator, CURVE // handshake boxes that fail to open, a server's ERROR command seen by // a client, or any ZAP handler rejection. Surfaces on // monitor channels as EventHandshakeFailedAuth. ErrAuthFailed = zmqerr.ErrAuthFailed // ErrMalformedFrame reports a frame that violates ZMTP framing rules // or exceeds [WithMaxMessageSize]. From the wire, the session is torn // down and the error surfaces via the monitor channel rather than // through a Send/Recv call. On the send side, SendMsg returns it // synchronously for a frame over WithMaxMessageSize, without touching // the session. ErrMalformedFrame = zmqerr.ErrMalformedFrame // ErrProtocolVersion is returned when the peer's greeting advertises // a ZMTP major version gozmq does not speak (anything other than 3). // Surfaces as EventHandshakeFailedProtocol on the monitor channel. ErrProtocolVersion = zmqerr.ErrProtocolVersion // ErrRouteUnknown is returned by a ROUTER send whose leading identity // frame matches no connected peer (including one that has just // disconnected) when [WithRouterMandatory] is enabled; without it the // message is dropped silently and counted in Metrics. A message with // no identity frame at all always returns it. STREAM sends always // behave as mandatory. ErrRouteUnknown = zmqerr.ErrRouteUnknown // ErrEndpointInvalid is returned by Bind or Connect when the // endpoint string is syntactically invalid for the chosen transport // (bad port, empty inproc name, malformed ipc path, etc.). ErrEndpointInvalid = zmqerr.ErrEndpointInvalid // ErrEndpointUnknown is returned by Disconnect when the endpoint // does not match any active Connect target, and by Unbind when it // does not match any active listener. Distinct from // ErrEndpointInvalid, which signals a syntactically bad endpoint. ErrEndpointUnknown = zmqerr.ErrEndpointUnknown // ErrTransportUnknown is returned by Bind or Connect when the // endpoint's scheme has no transport registered on the Context — for // example tls+tcp:// without a prior Context.RegisterTransport call // that installs a TLS transport. ErrTransportUnknown = zmqerr.ErrTransportUnknown // ErrNonceExhausted is returned by a CURVE-secured session when its // per-direction short-nonce counter would wrap. RFC 26 defines // uint64 counters starting at 1 and expects rekeying long before // wrap; gozmq does not implement rekey, so the session is torn down // cleanly with this sentinel, which is logged through [WithLogger] (the // EventDisconnected it causes carries no reason). Operators seeing it // should rotate keys and/or reconnect. ErrNonceExhausted = zmqerr.ErrNonceExhausted )
Sentinel errors returned across the public API. An error that reports a gozmq condition (closed socket, lock-step violation, unknown route, handshake or wire failure, bad endpoint) wraps one of these, so callers can dispatch with errors.Is instead of string-matching. Errors that originate elsewhere are not rewrapped:
- A blocking call whose context ends returns ctx.Err() as is (context.Canceled or context.DeadlineExceeded).
- Operating-system and network errors from a transport — Bind on an address in use, a failed STREAM dial — are returned as the underlying error (typically a *net.OpError); use errors.As.
- Context.NewSocket and Proxy report invalid configuration (option values and combinations, socket pairings) with plain descriptive errors.
- A ZAP handler's rejection always wraps ErrAuthFailed, with the handler's own error kept in the chain.
Failures on an established session do not reach SendMsg or RecvMsg: the session is torn down and the error surfaces on the monitor channel.
These are variable aliases for the authoritative values in internal/zmqerr (to break the import cycle where internal packages wrap sentinels and the public gozmq package imports those internal packages for wiring). errors.Is sees them as the same value.
Functions ¶
func Proxy ¶
Proxy shuttles messages between two sockets in both directions until ctx is cancelled or a socket fails, the equivalent of libzmq's zmq_proxy.
Everything Recv'd on frontend is Sent on backend and vice versa, frames intact. Because the whole multipart message is moved as one *Msg, routing envelopes survive the hop unchanged — which is what makes the classic device topologies work:
XSUB → XPUB a pub/sub forwarder. Subscriptions travel upstream on
their own because XPUB surfaces its subscribers'
SUBSCRIBE and CANCEL as ordinary messages and XSUB
forwards them upstream; no special casing here.
ROUTER → DEALER a request/reply broker. The ROUTER-prepended identity
frame rides along, so replies find their way back.
PULL → PUSH a pipeline forwarder.
Half-duplex patterns are handled by only running the direction that can work: a PUB or PUSH is never received from, a SUB or PULL never sent to. A pairing with no workable direction at all (PUB with PUSH, say) is a configuration error and returns immediately.
If capture is non-nil, every forwarded message is also sent to it — the usual pattern is a PUB socket for tapping traffic. Capture runs on its own goroutine behind a bounded queue, so a tap that keeps up sees every message, and one that stalls or fills its high-water mark drops rather than applying backpressure to the data path. Capture errors never fail the proxy, and a capture socket that blocks never delays its return: taps still queued or in flight when Proxy stops may be dropped.
Proxy blocks until it stops. It returns nil for the expected shutdown — ctx cancellation, or either socket being closed by another goroutine — and the underlying error otherwise. Both directions are torn down before it returns, but the sockets themselves are left open; closing them is the caller's job.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = gozmq.Proxy(ctx, frontend, backend, nil) }()
The two directions run on their own goroutines, so a socket handed to Proxy must not be used concurrently by the caller.
Example ¶
ExampleProxy is the XSUB/XPUB forwarder from the README: publishers connect to one stable address, subscribers to another, and either side can come and go without the other reconfiguring.
Subscriptions travel upstream through the proxy without any special handling — XPUB surfaces each SUBSCRIBE as a message and Proxy forwards it to XSUB, which re-emits it to the real publisher.
package main
import (
"context"
"fmt"
"time"
"github.com/exergy-dev/gozmq"
)
func main() {
zctx := gozmq.NewContext()
defer zctx.Close()
// The upstream publisher.
pub, _ := zctx.NewSocket(gozmq.Pub)
defer pub.Close()
_ = pub.Bind("inproc://example-proxy-up")
// The proxy's two faces.
xsub, _ := zctx.NewSocket(gozmq.XSub)
defer xsub.Close()
_ = xsub.Connect("inproc://example-proxy-up")
xpub, _ := zctx.NewSocket(gozmq.XPub)
defer xpub.Close()
_ = xpub.Bind("inproc://example-proxy-down")
proxyCtx, stop := context.WithCancel(context.Background())
defer stop()
go func() { _ = gozmq.Proxy(proxyCtx, xsub, xpub, nil) }()
// A subscriber on the far side.
sub, _ := zctx.NewSocket(gozmq.Sub, gozmq.WithSubscribe([]byte("topic.")))
defer sub.Close()
_ = sub.Connect("inproc://example-proxy-down")
callCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// PUB drops messages published before a subscription has propagated,
// and here it has two hops to travel, so republish until one lands.
for {
_ = pub.SendBytes(callCtx, []byte("topic.a|hello"))
attempt, cancelAttempt := context.WithTimeout(callCtx, 100*time.Millisecond)
got, err := sub.RecvBytes(attempt)
cancelAttempt()
if err == nil {
fmt.Printf("%s\n", got)
break
}
if callCtx.Err() != nil {
fmt.Println("subscription never propagated")
break
}
}
}
Output: topic.a|hello
Types ¶
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is the top-level resource owner. A Context holds the scheme to transport table, the inproc namespace shared by all inproc sockets on this Context, and the optional ZAP handler. Contexts share nothing with each other.
The zero value is NOT usable; construct via NewContext.
func NewContext ¶
func NewContext(opts ...ContextOption) *Context
NewContext creates a new Context. Call Close to release resources.
Example (PairRoundTrip) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/exergy-dev/gozmq"
)
func main() {
ctx := gozmq.NewContext()
defer ctx.Close()
server, _ := ctx.NewSocket(gozmq.Pair)
defer server.Close()
_ = server.Bind("inproc://example-pair")
client, _ := ctx.NewSocket(gozmq.Pair)
defer client.Close()
_ = client.Connect("inproc://example-pair")
callCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = client.SendBytes(callCtx, []byte("ping"))
msg, _ := server.RecvMsg(callCtx)
fmt.Printf("%s\n", msg.Bytes())
msg.Release() // always Release received messages
}
Output: ping
Example (ReqRep) ¶
package main
import (
"bytes"
"context"
"fmt"
"time"
"github.com/exergy-dev/gozmq"
)
func main() {
ctx := gozmq.NewContext()
defer ctx.Close()
rep, _ := ctx.NewSocket(gozmq.Rep)
defer rep.Close()
_ = rep.Bind("inproc://example-reqrep")
req, _ := ctx.NewSocket(gozmq.Req)
defer req.Close()
_ = req.Connect("inproc://example-reqrep")
callCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = req.SendBytes(callCtx, []byte("hello"))
request, _ := rep.RecvMsg(callCtx)
_ = rep.SendBytes(callCtx, append(bytes.Clone(request.Bytes()), []byte(" world")...))
request.Release()
reply, _ := req.RecvMsg(callCtx)
fmt.Printf("%s\n", reply.Bytes())
reply.Release()
}
Output: hello world
func (*Context) Close ¶
Close cancels the Context and tears down every socket created on it. It is idempotent; subsequent Close calls return nil. Subsequent NewSocket calls return ErrContextClosed.
func (*Context) Ctx ¶
Ctx returns the Context's cancellation context. Blocking API calls that accept a context.Context honor this root cancellation.
func (*Context) NewSocket ¶
func (c *Context) NewSocket(t SocketType, opts ...Option) (*Socket, error)
NewSocket constructs a socket of the given type on this Context.
func (*Context) RegisterTransport ¶
RegisterTransport installs t in the Context's transport registry. The transport's Scheme() determines which endpoint prefix it handles; registering a transport for an already-registered scheme overwrites the prior entry.
A Context starts with tcp, tcp6 and ipc already registered, so this is needed in two cases. inproc:// is not a transport: the Context joins inproc sockets directly, and registering a transport whose Scheme is "inproc" panics (a programmer error).
The first is a built-in transport that needs caller-supplied configuration. TLS is the main one — there is no reasonable default *tls.Config, so tls+tcp is not preregistered:
tr, err := transport.NewTLSTransport(tlsCfg)
if err != nil {
return err
}
ctx := gozmq.NewContext()
ctx.RegisterTransport(tr)
sock, _ := ctx.NewSocket(gozmq.Router)
_ = sock.Bind("tls+tcp://0.0.0.0:5555")
It also re-registers a built-in whose exported knobs you want to change — for example TCP keepalive or socket buffer sizes:
tcp := transport.NewTCPTransport() tcp.KeepAlivePeriod = 10 * time.Second ctx.RegisterTransport(tcp) // replaces the default tcp:// entry
The second is a scheme gozmq does not ship. transport.Transport is a public interface naming only standard-library types, so an out-of-tree carrier (QUIC, WebSocket, a fault-injecting test harness) can be plugged in without forking. Everything above the transport — sessions, ZMTP framing, security mechanisms, socket patterns — is unaffected.
Safe to call concurrently with NewSocket; existing sockets consult the registry at Bind / Connect time, so a socket constructed before RegisterTransport sees the updated scheme set as long as its Bind / Connect call races after Register.
type ContextOption ¶
type ContextOption interface {
// contains filtered or unexported methods
}
ContextOption configures a Context at construction.
func WithZAPHandler ¶
func WithZAPHandler(handler security.ZAPHandler) ContextOption
WithZAPHandler installs a context-level RFC 27 ZAP handler. It authorizes the peer on the server side of every PLAIN and CURVE handshake, whether that socket binds or connects (the PLAIN/CURVE role comes from the options, not the transport direction), and on the accepting side of NULL handshakes on sockets with a WithZAPDomain. It is called directly on each connection's handshake goroutine, concurrently across connections, with no timeout and no panic recovery: a handler that blocks holds that connection (and a later Close of its socket) until it returns, one that panics crashes the process, and one that calls Close on the socket being handshaken deadlocks. A rejection fails the handshake with an error wrapping the handler's own. A nil handler removes it.
type Event ¶
type Event struct {
// Type is the event kind. Consumers should treat unknown values
// defensively because new kinds may be added in minor versions.
Type EventType
// Endpoint is the endpoint string the event relates to. For
// server-side events (Accepted, Disconnected on an accepted session)
// this is the peer's remote endpoint; for client-side events it is
// the configured connect target; for bind events it is the
// resolved bind endpoint.
Endpoint string
// Time is the wall-clock timestamp at which the event was emitted.
Time time.Time
// Reason is an error string explaining failure events (EventBindFailed,
// EventAcceptFailed, EventHandshakeFailed*) or the pending backoff for
// EventConnectDelayed/Retried. It is empty for EventDisconnected, even
// when the session was torn down for a protocol error: that cause is
// logged through [WithLogger]. Empty for success events such as
// EventConnected, EventListening, and EventHandshakeSucceeded.
Reason string
}
Event is a single lifecycle notification delivered on a monitor channel registered via WithMonitor or Socket.Monitor. Type, Endpoint and Time are set for every event; Reason only where noted below. Never close a monitor channel (see Socket.Monitor).
type EventType ¶
type EventType uint32
EventType classifies lifecycle events emitted on a socket's monitor channel. The kinds mirror libzmq's ZMQ_EVENT_* set, but the numeric values are gozmq's own and are not the libzmq constants; new kinds may be appended, so consumers should handle unknown values gracefully. EventType is a bitmask so consumers can subscribe to a subset of event kinds via WithMonitor or Socket.Monitor.
const ( // EventConnected fires on a client-side socket after a dial plus // ZMTP handshake completes and the session's pipe is attached to // the engine; on inproc, once the Connect is joined to its Bind. // Event.Endpoint is the configured connect target. EventConnected EventType = 1 << iota // EventConnectDelayed fires on the first reconnect attempt following // a dial or handshake failure. Event.Endpoint is the target; // Event.Reason carries the pending backoff duration in string form. EventConnectDelayed // EventConnectRetried fires on the second and subsequent reconnect // attempts, distinguishing ongoing trouble from first trouble. // Event.Endpoint is the target; Event.Reason carries the pending // backoff duration. EventConnectRetried // EventConnectFailed fires when Connect fails terminally with no // reconnect loop to fall back on: an unknown transport scheme, a // STREAM dial failure (STREAM dials exactly once), or an inproc // Connect refused by its peer (an incompatible socket type, possibly // found only when a waiting Connect meets its Bind). Event.Endpoint is // the requested target; Event.Reason is the underlying error string. EventConnectFailed // EventListening fires after a successful Bind with wildcards and // ephemeral ports resolved. Event.Endpoint is the resolved endpoint // (same value as Socket.LastEndpoint). EventListening // EventBindFailed fires when Bind cannot complete — unknown // transport scheme, invalid endpoint, or a net.Listen error. // Event.Endpoint is the requested (unresolved) endpoint; // Event.Reason is the underlying error string. EventBindFailed // EventAccepted fires on a server-side socket when a new peer // connection is accepted off the listener, before the ZMTP // handshake begins; on inproc, when a Connect is joined to this Bind. // Event.Endpoint is the peer's remote endpoint (for inproc, the bound // endpoint). EventAccepted // EventAcceptFailed fires for each non-terminal accept error (EMFILE, // an out-of-tree transport's per-connection error, ...); the accept // loop keeps running and retries with capped backoff. A failed TLS // handshake is not an accept error: it runs inside the ZMTP handshake // and surfaces as EventHandshakeFailedProtocol. Event.Endpoint is the // bound endpoint; Event.Reason carries the underlying error. EventAcceptFailed // EventClosed fires once Socket.Close has completed its teardown // sequence. Event.Endpoint is the most recent bind endpoint (may // be empty for connect-only sockets). EventClosed // EventDisconnected fires when a previously-connected session is // torn down — peer closed, heartbeat timeout, or local // Socket.Close, or an inproc Disconnect on either side. Event.Endpoint // is the remote peer endpoint (for inproc, the endpoint name). EventDisconnected // EventHandshakeSucceeded fires after the ZMTP greeting and // security handshake complete successfully on either side of a // session. Event.Endpoint is the connect target (client) or peer // remote (server). Event.Reason is empty. EventHandshakeSucceeded // EventHandshakeFailedProtocol fires when the handshake aborts due // to a protocol-level problem: unsupported ZMTP version, malformed // greeting or command, handshake timeout, or an unexpected peer // drop. Event.Reason carries the underlying error string. EventHandshakeFailedProtocol // EventHandshakeFailedAuth fires when the handshake aborts because // the security mechanism rejected the peer — PLAIN credentials // refused, CURVE box authentication failure, or ZAP denial. // Event.Reason carries the underlying error string. EventHandshakeFailedAuth // EventAll is the bitmask of every event type defined above. Pass // it as the mask argument to [WithMonitor] or [Socket.Monitor] to // receive every lifecycle event. EventAll EventType = 0xFFFFFFFF )
type Msg ¶
Msg is a ZMTP multipart message. Frames delivered by RecvMsg are ordinary Go memory owned by the caller: safe to retain, stash, re-send, or pass between goroutines, and reclaimed by the garbage collector; (*Msg).Release and Retain do nothing for them. The exception is a socket created with WithRecvBufferPool, whose large frames are lent until Release (see that option and the msg package's "Lent frames").
Msg is an alias for msg.Msg; see that package for the full method set. There is no need to import it — the alias makes every method reachable as gozmq.Msg, and the NewMsg* constructors below cover construction.
func NewMsgFromBytes ¶
NewMsgFromBytes wraps b in a single-frame message (no copy).
func NewMsgFromFrames ¶
NewMsgFromFrames wraps the provided frames in a multipart message.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures a Socket at construction time. The option type is opaque; construct values via the With* helpers. Options that are inapplicable to the socket type are rejected with an error at Socket construction rather than silently ignored: pattern-specific options (WithRouterMandatory, WithXPubVerbose, WithSubscribe) on the wrong pattern, and ZMTP-layer options (security, heartbeat, identity, handshake timeout, ZAP domain) on STREAM sockets, which bypass ZMTP entirely.
func WithCurveClient ¶
WithCurveClient configures the socket as the client side of a CURVE handshake. serverKey is the expected server long-term public key (clients authenticate the server by this pinned key); publicKey/secretKey is this client's long-term keypair, which the server uses to authenticate the client. All three arguments must be 32 raw bytes each; decode from Z85 first if stored textually. The resulting channel is forward-secret (ephemeral session keys) and mutually authenticated. As with WithCurveServer, inproc:// is ruled out.
func WithCurveServer ¶
WithCurveServer configures the socket as the server side of a CURVE (CurveZMQ) handshake using secretKey as its long-term private key. secretKey must be 32 raw bytes (decode from Z85 via the security/curve package if you store keys in the standard textual format). CURVE provides forward-secret AEAD encryption; the client authenticates the server by its pinned public key, and the handshake proves that the client holds the secret half of the public key it presents. Which client keys are *allowed* is not decided here: without a WithZAPHandler on the Context every client that completes the handshake is accepted. Install a ZAP handler that checks the client's public key (the ZAP request's credential) to authorize clients. inproc runs no mechanism, so a CURVE socket cannot Bind or Connect on inproc:// (the call fails with ErrEndpointInvalid).
func WithHandshakeTimeout ¶
WithHandshakeTimeout caps the total duration of the ZMTP handshake, covering the greeting exchange plus the security mechanism handshake (NULL, PLAIN, or CURVE) and the READY metadata exchange; on tls+tcp it also bounds the TLS handshake, which runs lazily inside it. Default is 30 seconds; 0 disables the limit. On timeout the session is torn down with ErrHandshakeTimeout and, on a client socket, the reconnector retries with the configured backoff.
func WithHeartbeat ¶
WithHeartbeat configures the ZMTP 3.1 heartbeat. interval is how often PING commands are sent on an otherwise-idle session; timeout is the duration without any inbound frame (data or PONG) after which the peer is considered dead and the session is torn down. Defaults: 30s interval, 90s timeout. A timeout of 0 means 3× interval; an interval of 0 disables heartbeats. Heartbeats are disabled automatically when the peer advertises ZMTP 3.0 in the greeting. Heartbeating is the only reliable way to detect a half-open TCP connection (e.g. a peer killed without a FIN, or a NAT that dropped the flow) — disabling it is discouraged on long-lived connections.
func WithIdentity ¶
WithIdentity sets the ROUTER/DEALER identity advertised during the ZMTP handshake. The identity is the peer-visible name by which a ROUTER addresses this DEALER (or by which a ROUTER peer appears in the leading frame of a routed message). Identity bytes must be either empty (the default: a ROUTER peer then synthesizes a 5-byte identity with a zero leading byte) or 1..255 bytes long with a non-zero leading byte; longer or zero-prefixed identities are rejected by NewSocket. The slice is copied defensively.
func WithLinger ¶
WithLinger sets the grace period Socket.Close waits for outbound pipes to flush queued messages to the wire. Default is 1 second. Zero discards any queued messages immediately on Close. A negative duration blocks Close indefinitely until every peer has drained, matching libzmq's infinite-linger behavior — this can deadlock Close if a peer never drains or reconnects, so pair it with Socket.CloseCtx, whose context bounds the wait.
func WithLogger ¶
WithLogger sets the *slog.Logger used for internal diagnostics emitted by this socket and its child sessions — handshake failures, reconnect attempts, heartbeat loss, and teardown anomalies. Default is slog.Default. Passing nil resets to the process default.
func WithMaxMessageSize ¶
WithMaxMessageSize sets the per-message byte limit: the total length of all frames of one logical message. Default is 64 MiB. (libzmq's ZMQ_MAXMSGSIZE is per frame; gozmq bounds the whole message on both sides so that a sender's check and a receiver's check agree.) It is enforced in both directions, with different surfacing:
- Send side: SendMsg/SendBytes sum the frames up front and return a synchronous error wrapping ErrMalformedFrame on overflow; the session is NOT torn down.
- Recv side: a peer whose message exceeds the limit has its session torn down. The read loop detects it asynchronously of the application's call path, so it surfaces as an EventDisconnected (with no reason) and a log line through WithLogger, not as a Recv error.
For CURVE the limit applies to the plaintext; the session allows for the mechanism's per-frame overhead on the wire. Memory for an inbound frame is allocated as its bytes arrive, so a peer that announces a huge frame and stalls costs little; the cap bounds what a completed message may occupy.
Pass 0 to disable the limit — NOT recommended for untrusted peers.
func WithMonitor ¶
WithMonitor registers a channel to receive lifecycle [Event]s whose Type bit is set in mask. Use EventAll to receive every event kind. The channel must be buffered: events are delivered non-blocking, and when the channel is full the event is dropped rather than blocking the socket's hot path. A buffer of 64-256 events is recommended; consumers that lag materially are responsible for their own drops. Never close the channel: events are emitted from session goroutines and one may still be in flight after Socket.Monitor (nil) or Close returns. Stop reading and let it be garbage collected instead.
func WithPlainAuth ¶
WithPlainAuth makes the socket the PLAIN server and installs its credential validator. The callback is invoked for each handshake with the credentials the client sent; returning true allows the session, false rejects it with ErrAuthFailed. When the Context has a WithZAPHandler, that handler decides instead. As with libzmq's ZMQ_PLAIN_SERVER, the PLAIN role is independent of Bind/Connect: the socket is the server on every connection. It cannot be combined with WithPlainClient or the CURVE options.
The callback runs on the connection's handshake goroutine with no timeout and no panic recovery: keep it quick, never call Close on the socket from it, and compare secrets in constant time.
PLAIN credentials traverse the wire in cleartext — only use this mechanism on a trusted link (ipc, loopback) or wrapped in tls+tcp://. For untrusted networks prefer WithCurveServer / WithCurveClient. As in libzmq, inproc runs no mechanism: Bind or Connect on inproc:// fails with ErrEndpointInvalid for a socket with any PLAIN or CURVE option.
func WithPlainClient ¶
WithPlainClient makes the socket the PLAIN client, presenting (username, password) to the server during the ZMTP handshake. The PLAIN role is independent of Bind/Connect: the socket is the client on every connection, including those it accepts. It cannot be combined with WithPlainAuth or the CURVE options. Credentials are sent in cleartext; wrap in tls+tcp:// or switch to CURVE for any network you do not trust. Like every mechanism, it rules out inproc:// (see WithPlainAuth).
func WithReconnectInterval ¶
WithReconnectInterval sets the base delay between reconnection attempts on a client-side socket after a dial failure or post-handshake disconnect. Default is 100ms; zero selects the default rather than an immediate retry. The actual delay grows exponentially and is jittered by 20% before each attempt, capped by WithReconnectIntervalMax.
func WithReconnectIntervalMax ¶
WithReconnectIntervalMax caps the reconnection backoff. Default is 30 seconds. Zero removes the cap: backoff doubles without bound, so after a long outage a socket may wait arbitrarily long between attempts. NOTE this diverges from libzmq, where ZMQ_RECONNECT_IVL_MAX=0 (its default) means "no exponential backoff, constant interval".
func WithRecvBufferPool ¶
WithRecvBufferPool, when enabled, receives inbound frames larger than 4 KiB into buffers drawn from a shared, size-tiered pool instead of a fresh allocation per frame, which saves the allocation and garbage collection cost that dominates large-frame throughput. Default is false.
It changes the ownership of received messages, which is why it is opt-in. A message carrying pooled frames is lent (see [Msg.Lent]):
- The receiver holds one reference and must call [Msg.Release] when done with the message; [Msg.Retain] adds a reference, each needing its own Release.
- The frames — including any slice taken from Frames, Bytes or SingleFrame — are valid only until the last reference is released. Their buffers then go back to the pool and are overwritten by later receives, so copy anything that must outlive the message.
- Forwarding is safe: Socket.SendMsg holds its own reference until the message is written, so RecvMsg, SendMsg, Release is correct. Build a forwarded message with [Msg.Derive], never by wrapping the frames in NewMsgFromBytes or NewMsgFromFrames.
- Forgetting Release is safe: there is no finalizer, so the buffer is simply collected by the garbage collector instead of being reused.
- Releasing more times than retained panics.
Smaller frames, and frames on CURVE or custom-mechanism sessions (whose decoding produces a fresh plaintext anyway), are always ordinary memory, for which Release does nothing. The option affects receiving only, and is not applicable to STREAM sockets.
func WithRecvHWM ¶
WithRecvHWM sets the inbound high-water mark — the maximum number of messages buffered per peer pipe before the reader goroutine stops accepting frames from the wire and exerts TCP backpressure on the peer. Default is 1000, maximum MaxHWM. Zero disables the limit. As with WithSendHWM, a positive HWM is allocated per peer connection.
On inproc, where one pipe joins the two sockets, each direction holds the sender's send HWM plus the receiver's recv HWM, and is unlimited if either is zero (as in libzmq).
func WithRouterMandatory ¶
WithRouterMandatory controls ROUTER.Send behaviour for unroutable destinations (leading identity frame not matching any connected peer). Default is false: unroutable messages are dropped silently, matching libzmq. When true, Send returns ErrRouteUnknown instead, which is the safer default for request/response services that need to observe delivery failures.
func WithSecurityMech ¶
func WithSecurityMech(newMech func(role security.Role, meta map[string]string) (security.Mech, error)) Option
WithSecurityMech installs a caller-supplied ZMTP security mechanism, bypassing the built-in NULL / PLAIN / CURVE selection entirely. It is mutually exclusive with WithPlainAuth, WithPlainClient, WithCurveServer, and WithCurveClient.
Reach for this only when the shipped mechanisms genuinely do not fit — a private protocol variant, or a fault-injecting test double. A security.Mech sits directly on the wire, so a mistake in it is a security bug rather than a correctness bug, and a mechanism gozmq does not ship will not interoperate with libzmq or any other ZMTP peer. If what you actually need is control over *which* peers are allowed rather than how the handshake works, use WithZAPHandler instead and keep the vetted cryptography.
newMech is called once per session, with the session's role and with the local metadata gozmq advertises in READY (Socket-Type, and Identity when WithIdentity is set). The mechanism must include those properties in its own Metadata, and report the peer's through PeerMetadata once the handshake is done; the simplest way is to pass the map straight through to security.NewMechBase, embed the result, and call its MergePeerMetadata. Returning an error fails the session — gozmq never falls back to a weaker mechanism.
Each inbound handshake frame is capped at 64 KiB, whatever WithMaxMessageSize says, so an unauthenticated peer cannot make the socket allocate more. inproc runs no handshake, so a socket with a custom mechanism cannot Bind or Connect on inproc:// (the call fails with ErrEndpointInvalid).
func WithSendHWM ¶
WithSendHWM sets the outbound high-water mark — the maximum number of messages queued per peer pipe before backpressure engages. Default is 1000, maximum MaxHWM. Zero disables the limit (unbounded growth; not recommended for untrusted peers). A positive HWM is the capacity of a channel allocated per peer connection, so very large values cost memory up front. When the HWM is reached, Send behavior depends on the socket pattern: blocking sockets (PAIR, PUSH, DEALER, REQ, REP, ROUTER) wait for a Recv on the peer to drain queue space, while PUB/XPUB drop the message for the full peer and continue the fan-out (the drop is counted in Socket.Metrics).
func WithSubscribe ¶
WithSubscribe adds a subscription prefix to a SUB (or XSUB) socket. May be passed multiple times to subscribe to disjoint prefixes. An empty prefix subscribes to every message. Subscriptions are refcounted: calling Subscribe or passing WithSubscribe for the same prefix twice requires two matching Unsubscribe calls before the prefix is actually removed from the filter and a CANCEL is sent upstream to connected publishers. This enables independent components on the same socket to manage their own subscriptions without interfering.
func WithXPubVerbose ¶
WithXPubVerbose controls subscription deduplication on XPUB. Default is false: XPUB surfaces a SUBSCRIBE or CANCEL to the application only when it is the first/last reference to that prefix across all connected SUB peers (the refcounted view). When true, every SUBSCRIBE/CANCEL from any peer is forwarded to the application as a discrete message — useful for applications that track subscriber churn or implement their own authorization on subscriptions.
func WithZAPDomain ¶
WithZAPDomain sets the RFC 27 ZAP domain presented to the Context's WithZAPHandler when it authorizes this socket's peers. PLAIN and CURVE servers consult the handler whatever the domain; NULL sockets consult it, for the connections they accept, only when a domain is set, as in libzmq, so a handler installed for PLAIN or CURVE does not start vetting every NULL socket. The default is the empty domain.
type PollEvent ¶
type PollEvent struct {
// Socket is the *gozmq.Socket the caller passed to Poller.Add.
Socket *Socket
// Events is the set of ready directions among the registered mask.
Events PollEvents
}
PollEvent reports that a Poller-registered Socket has at least one of its registered interest events ready. Events is the intersection of the registration mask and the engine's current readiness — it never contains bits the caller did not register.
type PollEvents ¶
type PollEvents uint8
PollEvents is a bitmask of interest sets passed to Poller.Add and surfaced inside PollEvent when Poll reports readiness. The bit values match the libzmq ZMQ_POLLIN / ZMQ_POLLOUT convention so they are easy to mentally translate between gozmq and zmq_poll-style code.
const ( // PollIn signals interest in (or readiness of) inbound messages — // a RecvMsg on the socket is expected not to block on queue // emptiness. PollIn PollEvents = 1 << 0 // PollOut signals interest in (or readiness of) outbound capacity — // a SendMsg has at least one attached peer to dispatch to. UNLIKE // libzmq's ZMQ_POLLOUT (which only reports ready when a message can // be queued without blocking), gozmq's PollOut does NOT consider HWM // pressure: SendMsg after a PollOut wakeup may still block if every // peer pipe is full. Event loops ported from zmq_poll should pair // PollOut with a Send deadline or context. PollOut PollEvents = 1 << 1 )
type Poller ¶
type Poller struct {
// contains filtered or unexported fields
}
Poller multiplexes readiness across many sockets, equivalent in spirit to libzmq's zmq_poll: register N sockets with interest sets, then call Poll to block until at least one has at least one of its registered events ready.
Concurrency: Add, Remove, and Poll are individually safe for concurrent use by multiple goroutines (serialised by the Poller's mutex). The conventional usage is still single-threaded — one goroutine owns the Poller and uses Poll as its main event loop.
Readiness model: this is non-consuming. A Poll call reports that a Recv (resp. Send) is unlikely to block on emptiness (resp. peer absence); the caller is still responsible for actually invoking Socket.RecvMsg / Socket.SendMsg on the returned sockets. Subsequent Poll calls return fresh readiness — there is no latched edge-trigger state between calls.
Engine support: every built-in socket type exposes non-consuming readiness signals to the Poller.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/exergy-dev/gozmq"
)
func main() {
ctx := gozmq.NewContext()
defer ctx.Close()
pullA, _ := ctx.NewSocket(gozmq.Pull)
defer pullA.Close()
_ = pullA.Bind("inproc://example-poller-a")
pullB, _ := ctx.NewSocket(gozmq.Pull)
defer pullB.Close()
_ = pullB.Bind("inproc://example-poller-b")
push, _ := ctx.NewSocket(gozmq.Push)
defer push.Close()
_ = push.Connect("inproc://example-poller-b")
callCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = push.SendBytes(callCtx, []byte("ready"))
poller := gozmq.NewPoller()
poller.Add(pullA, gozmq.PollIn)
poller.Add(pullB, gozmq.PollIn)
// Poll blocks until at least one registered socket is readable —
// here only pullB, since nothing was sent to pullA.
events, _ := poller.Poll(callCtx)
for _, ev := range events {
msg, _ := ev.Socket.RecvMsg(callCtx)
fmt.Printf("%s\n", msg.Bytes())
msg.Release()
}
}
Output: ready
func NewPoller ¶
func NewPoller() *Poller
NewPoller returns an empty Poller. Sockets are registered via Add.
func (*Poller) Add ¶
func (p *Poller) Add(sock *Socket, events PollEvents)
Add registers sock with the given interest mask. If sock is already registered, Add replaces the existing mask. events == 0 leaves the socket present in the registration table but with no interest set — equivalent to Remove + Add(sock, 0). Most callers prefer Remove for clarity.
func (*Poller) Poll ¶
Poll blocks until at least one registered socket has at least one of its registered events ready, or ctx is cancelled. On return the slice contains exactly the ready sockets with their ready event bits (a strict subset of each registration mask). The slice is caller-owned; the Poller does not retain it.
Empty-registration behaviour: if no sockets are registered (or all registered sockets have events == 0), Poll blocks until ctx fires and returns ctx.Err(). This matches libzmq's behaviour for an empty poll set; callers should usually treat it as a configuration error.
Closed sockets: a socket closed after Add but before Poll is effectively unregistered for the duration of that Poll call; it cannot become ready again. Callers may Remove the closed socket afterwards.
Spurious wakeups: under heavy churn (e.g. a peer attaches and immediately detaches between the wake and the readiness scan) Poll may loop internally and wait again. It never returns an empty event slice with a nil error.
Cost: Poll parks via reflect.Select over the registered ready channels. The reflection step is necessary because the registered set is dynamic and the gates come from heterogeneous engine types. The registration snapshot and SelectCase slice are cached across Poll calls (rebuilt only when the registration set changes or a registered socket closes), so steady-state Poll allocates only the result slice. Rough budget: comfortable for hundreds of registered sockets at thousands of Poll/sec; if you need higher rates, consolidate ready channels upstream (e.g. one dedicated goroutine per socket fanning into a single application channel) and avoid Poller in the hot path.
type Socket ¶
type Socket struct {
// contains filtered or unexported fields
}
Socket is the user-facing message endpoint.
Concurrency: SendMsg and RecvMsg are thread-safe (serialized by the engine). The idiomatic pattern is still one goroutine per socket.
The zero value is NOT usable; construct via Context.NewSocket.
Example (PubSub) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/exergy-dev/gozmq"
)
func main() {
ctx := gozmq.NewContext()
defer ctx.Close()
// An XPUB publisher surfaces each peer's SUBSCRIBE as a receivable
// message, letting the publisher wait for the subscription to arrive
// instead of sleeping (PUB/SUB's classic slow-joiner pitfall).
pub, _ := ctx.NewSocket(gozmq.XPub)
defer pub.Close()
_ = pub.Bind("inproc://example-pubsub")
sub, _ := ctx.NewSocket(gozmq.Sub, gozmq.WithSubscribe([]byte("weather")))
defer sub.Close()
_ = sub.Connect("inproc://example-pubsub")
callCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// Block until the subscription reaches the publisher, then publish.
subscribed, _ := pub.RecvMsg(callCtx)
subscribed.Release()
_ = pub.SendMsg(callCtx, gozmq.NewMsgFromFrames([]byte("weather"), []byte("sunny")))
msg, _ := sub.RecvMsg(callCtx)
fmt.Printf("%s %s\n", msg.Frames()[0], msg.Frames()[1])
msg.Release()
}
Output: weather sunny
Example (RouterDealer) ¶
package main
import (
"bytes"
"context"
"fmt"
"time"
"github.com/exergy-dev/gozmq"
)
func main() {
ctx := gozmq.NewContext()
defer ctx.Close()
router, _ := ctx.NewSocket(gozmq.Router)
defer router.Close()
_ = router.Bind("inproc://example-routerdealer")
dealer, _ := ctx.NewSocket(gozmq.Dealer, gozmq.WithIdentity([]byte("worker-1")))
defer dealer.Close()
_ = dealer.Connect("inproc://example-routerdealer")
callCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// Dealer → Router: the ROUTER receives [identity, payload].
_ = dealer.SendBytes(callCtx, []byte("job-42"))
request, _ := router.RecvMsg(callCtx)
identity := bytes.Clone(request.Frames()[0]) // copy before Release
fmt.Printf("%s sent %s\n", request.Frames()[0], request.Frames()[1])
request.Release()
// Router → Dealer: route the reply with the identity as leading frame.
_ = router.SendMsg(callCtx, gozmq.NewMsgFromFrames(identity, []byte("done")))
reply, _ := dealer.RecvMsg(callCtx)
fmt.Printf("%s\n", reply.Bytes())
reply.Release()
}
Output: worker-1 sent job-42 done
func (*Socket) Bind ¶
Bind listens on the given endpoint (e.g. "tcp://*:5555", "inproc://bar"). Returns ErrSocketClosed after Close.
func (*Socket) Close ¶
Close tears the socket down. Idempotent: repeated calls return nil, matching Context.Close and the io.Closer convention.
Close is equivalent to CloseCtx(context.Background()) and therefore cannot interrupt the linger drain. Callers using WithLinger(-1) (infinite) should use CloseCtx with a cancellable context instead.
Teardown order (LINGER drain):
- Quiesce reconnectors — stop re-dialing, but KEEP current sessions alive so their outbound queues can drain to the wire.
- Close listeners — no new accepts.
- Close the engine — nothing new is queued.
- Drain every link — session writers flush their queues to the conn and exit, leaving it open — and wait up to cfg.linger for them.
- Cancel the run context, then stop the reconnectors and links.
- Wait for the accept loops.
LINGER semantics:
- linger == 0: skip step 4 → queued messages may be lost.
- linger > 0: bounded wait; messages dropped after deadline.
- linger < 0: wait forever for drain (matches libzmq's infinite); cancellable only via CloseCtx.
func (*Socket) CloseCtx ¶
CloseCtx releases the socket and its peer connections. It drains outbound queues per WithLinger, but honors ctx.Done so callers with WithLinger(-1) can cancel an otherwise-infinite wait. Returns the first non-context error encountered during teardown; ctx.Err() is returned if cancellation interrupts the drain.
Cancellation semantics: if ctx fires while the linger drain is pending, the drain is abandoned but the remainder of teardown (session Stop, engine Close, runCancel, goroutine joins) still runs — callers observe a fully-closed Socket on return. Idempotent: a second call returns nil.
func (*Socket) Connect ¶
Connect dials the given endpoint. Returns ErrSocketClosed after Close. Connect starts a reconnect loop that survives transient dial failures and post-handshake disconnects, with exponential backoff + jitter per the configured WithReconnectInterval / WithReconnectIntervalMax.
An inproc Connect joins the bound socket directly. Before the Bind it waits, with no time limit, until the Bind, Disconnect or Close; an incompatible socket type is then reported as EventConnectFailed rather than returned.
Exception: STREAM sockets dial exactly once and do NOT reconnect — a dial failure is returned synchronously (with EventConnectFailed), and a later peer disconnect is final (surfaced via EventDisconnected). Reconnect supervision for raw STREAM peers is the application's responsibility.
func (*Socket) Disconnect ¶
Disconnect tears down every connection made by a Connect to exactly endpoint and stops reconnecting to it; an inproc Connect still waiting for its Bind is cancelled. Peers that connected to this socket are unaffected. Returns an error wrapping ErrEndpointUnknown when nothing matches.
func (*Socket) LastEndpoint ¶
LastEndpoint returns the endpoint of the most recent successful Bind, with wildcards resolved. Useful for recovering an ephemeral port.
func (*Socket) Metrics ¶
func (s *Socket) Metrics() SocketMetrics
Metrics returns a point-in-time snapshot of this socket's counters and queue-depth gauge. Safe to call from any goroutine. Returns the zero SocketMetrics if the socket has been closed.
func (*Socket) Monitor ¶
Monitor registers ch to receive Events matching mask, replacing any previously registered monitor channel (a socket has at most one). Passing a nil channel deregisters monitoring. ch must be buffered: events are delivered non-blocking and dropped when the channel is full, so the socket's hot path is never stalled by a slow consumer (see WithMonitor for sizing guidance). Never close a monitor channel: an emit already in flight on a session goroutine may still send to it after Monitor(nil) or Close returns. Let it be garbage collected.
func (*Socket) RecvBytes ¶
RecvBytes receives a single-frame message and returns an independent copy of its payload (inproc delivery can share frame bytes with the sender, e.g. PUB fan-out), releasing the message itself. Multipart messages return an error; use RecvMsg for those.
func (*Socket) RecvMsg ¶
RecvMsg blocks until a message arrives or ctx cancels. The returned frames are ordinary memory owned by the caller, except on a socket created with WithRecvBufferPool: there large frames are lent, valid until the message's final [Msg.Release] (see that option).
func (*Socket) SendBytes ¶
SendBytes sends a single-frame message containing b. It is a convenience shortcut equivalent to SendMsg(ctx, NewMsgFromBytes(b)).
func (*Socket) SendMsg ¶
SendMsg enqueues m for transmission per the socket's pattern policy.
m stays the caller's: for a lent message (see [Msg.Lent]) SendMsg takes its own reference for the send, released once the message has been written (or received and released by an inproc peer), so the caller may Release m as soon as SendMsg returns — the usual forwarding idiom is RecvMsg, SendMsg, Release. A plain message is sent as is; the caller must not modify its frames while it may still be in flight.
If WithMaxMessageSize is set (any positive cap), every frame in m is measured against the cap up front and the call returns an error wrapping ErrMalformedFrame on overflow — matching the per-frame body-length check enforced by the ZMTP codec (see zmtp/framing.go, WriteFrame). The synchronous check means oversize sends are visible to the caller without requiring a monitor channel and do not tear down the session.
func (*Socket) Subscribe ¶
Subscribe adds prefix to a SUB or XSUB socket's filter. Returns an error wrapping ErrFSMViolation on other socket types.
func (*Socket) Unbind ¶
Unbind stops listening on a previously-bound endpoint, matched against the resolved form returned by Bind (the same value LastEndpoint reports, with wildcards and ephemeral ports filled in). Established peer connections accepted from that listener are NOT torn down — only new accepts stop, matching libzmq's zmq_unbind. Returns an error wrapping ErrEndpointUnknown when no listener matches.
func (*Socket) Unsubscribe ¶
Unsubscribe decrements the refcount for prefix on a SUB or XSUB socket.
type SocketMetrics ¶
type SocketMetrics struct {
// Sent counts messages successfully handed to a peer pipe.
Sent uint64
// Recv counts messages successfully delivered to the application.
Recv uint64
// Dropped counts messages the engine refused to deliver after the
// caller's Send already returned successfully (see the drop
// semantics above).
Dropped uint64
// QueueDepth gauges the messages queued in the socket's inbound
// pipes at the instant Metrics was called.
QueueDepth uint64
}
SocketMetrics is a point-in-time snapshot of per-socket counters and gauges returned by (*Socket).Metrics.
Sent, Recv, and Dropped are monotonic uint64 counters read atomically. QueueDepth is a gauge sampled at the moment Metrics is called and reflects the number of messages queued in the socket's inbound pipes at that instant (zero for send-only patterns).
Drop semantics:
- PUB increments Dropped once per (message, peer) pair when the peer's pipe is at HWM during fan-out (slow-subscriber drop).
- ROUTER (non-mandatory) increments Dropped on a Send whose leading identity matches no attached peer.
Send-side errors returned to the caller do NOT count as drops — the caller already observed the failure and can decide what to do.
type SocketType ¶
type SocketType uint8
SocketType enumerates the ZMTP socket patterns.
const ( // Req is the lock-step request half of REQ/REP: strictly alternating // Send then Recv, load-balanced across connected REP/ROUTER peers. Req SocketType = iota + 1 // Rep is the lock-step reply half of REQ/REP: strictly alternating // Recv then Send, answering the peer the request arrived from. Rep // Dealer is the asynchronous REQ generalization: sends load-balance // across peers, receives fair-queue, no Send/Recv ordering rules. Dealer // Router is the asynchronous REP generalization: each received // message is prefixed with the peer's identity frame, and Send routes // by leading identity frame (see WithRouterMandatory). Router // Pub fans every sent message out to all subscribed peers; slow // subscribers at HWM are dropped per message. Pub never receives. Pub // Sub receives messages matching subscribed prefixes (see // Socket.Subscribe / WithSubscribe). Sub never sends. Sub // XPub is Pub plus visibility: subscription SUBSCRIBE/CANCEL messages // from peers surface via Recv (see WithXPubVerbose). XPub // XSub is Sub plus manual control: subscriptions are sent downstream // as explicit messages, enabling proxy topologies. XSub // Push pipelines sent messages round-robin across connected Pull // peers. Push never receives. Push // Pull fair-queues messages from connected Push peers. Pull never // sends. Pull // Pair is an exclusive 1:1 bidirectional link with no routing or // load-balancing; exactly one peer at a time. A peer disconnect is not // reported: Recv delivers what the old peer left buffered, then Send // and Recv wait for the next peer to attach. Pair // Stream exchanges raw TCP bytes with non-ZMQ peers: no ZMTP // handshake, framing, or security. Messages are [identity, payload] // pairs. See the Socket.Connect doc for its single-dial semantics. Stream )
func (SocketType) String ¶
func (t SocketType) String() string
String implements fmt.Stringer using the ZMTP "Socket-Type" metadata names; unknown values render as "SocketType(n)".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
monitor_events
command
Command monitor_events demonstrates socket lifecycle monitoring.
|
Command monitor_events demonstrates socket lifecycle monitoring. |
|
proxy_xsub_xpub
command
Command proxy_xsub_xpub demonstrates gozmq.Proxy as a PUB/SUB forwarder — the XSUB/XPUB "device" every ZeroMQ deployment eventually needs.
|
Command proxy_xsub_xpub demonstrates gozmq.Proxy as a PUB/SUB forwarder — the XSUB/XPUB "device" every ZeroMQ deployment eventually needs. |
|
security
command
Command security demonstrates an authenticated PAIR exchange with PLAIN (username and password) or CURVE (CurveZMQ keys, encrypted).
|
Command security demonstrates an authenticated PAIR exchange with PLAIN (username and password) or CURVE (CurveZMQ keys, encrypted). |
|
stream_echo
command
Command stream_echo demonstrates a STREAM socket talking to a plain TCP peer.
|
Command stream_echo demonstrates a STREAM socket talking to a plain TCP peer. |
|
typed_topicmux
command
Command typed_topicmux demonstrates the typed.TopicMux: one SUB socket receives two different struct types on different topic prefixes, and the mux dispatches each message to a typed handler.
|
Command typed_topicmux demonstrates the typed.TopicMux: one SUB socket receives two different struct types on different topic prefixes, and the mux dispatches each message to a typed handler. |
|
internal
|
|
|
bufpool
Package bufpool is the size-tiered []byte pool behind the opt-in receive buffer pool (gozmq.WithRecvBufferPool): the session reader reads large inbound frame bodies into buffers from Get and hands them to the application as lent msg.Msg frames whose release func Puts them back.
|
Package bufpool is the size-tiered []byte pool behind the opt-in receive buffer pool (gozmq.WithRecvBufferPool): the session reader reads large inbound frame bodies into buffers from Get and hands them to the application as lent msg.Msg frames whose release func Puts them back. |
|
pipe
Package pipe provides End, one side of the bidirectional in-memory message queue that connects a socket engine to a session (ZMTP or STREAM raw mode) or, on inproc, to another socket's engine.
|
Package pipe provides End, one side of the bidirectional in-memory message queue that connects a socket engine to a session (ZMTP or STREAM raw mode) or, on inproc, to another socket's engine. |
|
session
Package session implements the ZMTP per-peer state machine.
|
Package session implements the ZMTP per-peer state machine. |
|
socket
Package socket holds the per-pattern Engine implementations that back the public gozmq Socket types.
|
Package socket holds the per-pattern Engine implementations that back the public gozmq Socket types. |
|
testutil
Package testutil holds the test helpers shared by every package's tests.
|
Package testutil holds the test helpers shared by every package's tests. |
|
zmqerr
Package zmqerr holds the error sentinels returned across gozmq.
|
Package zmqerr holds the error sentinels returned across gozmq. |
|
zmtp
Package zmtp implements the wire-level constructs of ZeroMQ Message Transport Protocol 3.1: the framing layer (flags + length + body), the command codec, and the READY metadata codec, plus the FrameCodec / FrameHeaderAppender contracts those implement (see contracts.go), which the session layer consumes.
|
Package zmtp implements the wire-level constructs of ZeroMQ Message Transport Protocol 3.1: the framing layer (flags + length + body), the command codec, and the READY metadata codec, plus the FrameCodec / FrameHeaderAppender contracts those implement (see contracts.go), which the session layer consumes. |
|
Package msg defines Msg, the multipart ZMTP message exchanged by every gozmq socket.
|
Package msg defines Msg, the multipart ZMTP message exchanged by every gozmq socket. |
|
perf
|
|
|
zmqperf
command
Command zmqperf is the gozmq counterpart of libzmq's perf tools, one binary with four subcommands that pair up across two processes:
|
Command zmqperf is the gozmq counterpart of libzmq's perf tools, one binary with four subcommands that pair up across two processes: |
|
Package security hosts the ZMTP security mechanisms NULL and PLAIN plus the RFC 27 ZAP authorization codec.
|
Package security hosts the ZMTP security mechanisms NULL and PLAIN plus the RFC 27 ZAP authorization codec. |
|
curve
Package curve implements the CurveZMQ (RFC 26) security mechanism for gozmq.
|
Package curve implements the CurveZMQ (RFC 26) security mechanism for gozmq. |
|
Package transport defines the transport-layer contracts — Transport, Conn, and Listener — and provides the concrete implementations for the schemes gozmq ships: tcp, tcp6, ipc, and (opt-in) tls+tcp.
|
Package transport defines the transport-layer contracts — Transport, Conn, and Listener — and provides the concrete implementations for the schemes gozmq ships: tcp, tcp6, ipc, and (opt-in) tls+tcp. |
|
Package typed wraps a gozmq.Socket with generic helpers so callers can send and receive arbitrary Go values through a pluggable Codec instead of hand-rolling serialization and multipart framing at every call site.
|
Package typed wraps a gozmq.Socket with generic helpers so callers can send and receive arbitrary Go values through a pluggable Codec instead of hand-rolling serialization and multipart framing at every call site. |