nats

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 7 Imported by: 0

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

View Source
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

func New(conn *gonats.Conn, opts ...Option) *Adapter

New creates a new NATS adapter. The provided connection must already be established. Options can override defaults like the subject name.

func (*Adapter) Close

func (a *Adapter) Close() error

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

func (a *Adapter) Publish(ctx context.Context, msg wshub.AdapterMessage) error

Publish sends an AdapterMessage to all other subscribed nodes via NATS. It serializes the message as JSON.

func (*Adapter) Subscribe

func (a *Adapter) Subscribe(ctx context.Context, handler func(wshub.AdapterMessage)) error

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

func WithSubject(subject string) Option

WithSubject sets the NATS subject to publish and subscribe on. Default: "wshub.messages".

func WithUnmarshalErrorHandler added in v0.2.0

func WithUnmarshalErrorHandler(handler func(data []byte, err error)) Option

WithUnmarshalErrorHandler sets a callback to handle JSON unmarshal errors in the Subscribe callback. If not set, unmarshal errors are silently ignored.

Jump to

Keyboard shortcuts

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