Documentation
¶
Overview ¶
Package nats provides a NATS adapter for wshub multi-node communication. NATS offers lower latency than Redis Pub/Sub, making it well-suited for real-time WebSocket workloads.
Usage:
nc, _ := gonats.Connect("nats://localhost:4222")
adapter := nats.New(nc)
hub := wshub.NewHub(wshub.WithAdapter(adapter))
go hub.Run()
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("nats adapter: closed")
ErrClosed is returned when Publish or Subscribe is called after Close.
Functions ¶
This section is empty.
Types ¶
type Adapter ¶
type Adapter struct {
// contains filtered or unexported fields
}
Adapter implements wshub.Adapter using NATS core Pub/Sub. It is safe for concurrent use.
func New ¶
New creates a new NATS adapter. The provided connection must already be established. Options can override defaults like the subject name.
func (*Adapter) Close ¶
Close unsubscribes and releases resources. It does not close the underlying NATS connection — that remains the caller's responsibility. Close returns once the subscription's watcher goroutine has exited, so no goroutine started by Subscribe outlives it.
func (*Adapter) Publish ¶
Publish sends an AdapterMessage to all other subscribed nodes via NATS. It serializes the message as JSON.
func (*Adapter) Subscribe ¶
Subscribe begins receiving messages from NATS. The handler is called for every message received. Subscribe returns immediately — message delivery is handled by the NATS client's internal goroutine pool.
The subscription is stopped when the context is cancelled, Close is called, or the NATS connection is closed. Calling Subscribe again replaces the previous subscription, which is drained first. Subscribe returns ErrClosed if the adapter is closed.
type Option ¶
type Option func(*Adapter)
Option configures the NATS adapter.
func WithSubject ¶
WithSubject sets the NATS subject to publish and subscribe on. Default: "wshub.messages".
func WithUnmarshalErrorHandler ¶ added in v0.2.0
WithUnmarshalErrorHandler sets a callback to handle JSON unmarshal errors in the Subscribe callback. If not set, unmarshal errors are silently ignored.