Documentation
¶
Overview ¶
Package nats is a pure-Go (CGO_ENABLED=0) port of the Ruby nats-pure / nats client's public surface — the messaging client Ruby programs use to talk to a NATS server.
Upstream, the Ruby client speaks the NATS protocol over a socket it owns; this module keeps the same object model — Client, Msg, Subscription and the [Error] tree — but delegates the wire protocol to the official pure-Go client github.com/nats-io/nats.go. It does not reimplement the protocol.
MRI-faithful surface ¶
nc, _ := nats.Connect(nats.Servers("nats://127.0.0.1:4222"))
sub, _ := nc.Subscribe("greet.*", func(m *nats.Msg) {
m.Respond([]byte("hello, " + string(m.Data)))
})
rep, _ := nc.Request("greet.joe", []byte("joe"), time.Second)
fmt.Println(string(rep.Data)) // hello, joe
sub.Unsubscribe()
nc.Drain()
nc.Close()
The method names mirror the gem: Client.Publish, Client.Subscribe / Client.QueueSubscribe, Client.Request, Client.Flush, Client.Drain, Client.Close, and the connection callbacks Client.OnError, Client.OnReconnect and Client.OnDisconnect. Msg exposes Subject / Data / Reply / Header and Msg.Respond; errors map to the gem's classes (ErrTimeout is NATS::IO::Timeout, ErrNoResponders is NoRespondersError).
Host seam ¶
The transport is injectable. Connect dials a real server through nats.go by default, but the dialer is a seam: tests drive the whole client against an in-process broker (no socket) or an embedded nats-server started with github.com/nats-io/nats.go.InProcessServer. The core opens no external socket in unit tests.
Index ¶
- Variables
- type Client
- func (c *Client) Close()
- func (c *Client) Drain() error
- func (c *Client) Flush() error
- func (c *Client) FlushTimeout(timeout time.Duration) error
- func (c *Client) IsClosed() bool
- func (c *Client) OnClose(cb func())
- func (c *Client) OnDisconnect(cb func())
- func (c *Client) OnError(cb func(error))
- func (c *Client) OnReconnect(cb func())
- func (c *Client) Publish(subject string, data []byte) error
- func (c *Client) PublishMsg(m *Msg) error
- func (c *Client) PublishRequest(subject, reply string, data []byte) error
- func (c *Client) QueueSubscribe(subject, queue string, cb func(*Msg)) (*Subscription, error)
- func (c *Client) Request(subject string, data []byte, timeout time.Duration) (*Msg, error)
- func (c *Client) RequestMsg(m *Msg, timeout time.Duration) (*Msg, error)
- func (c *Client) Subscribe(subject string, cb func(*Msg)) (*Subscription, error)
- func (c *Client) Unsubscribe(sub *Subscription) error
- type Header
- type Msg
- type Option
- func ClosedCallback(cb func()) Option
- func DisconnectCallback(cb func()) Option
- func ErrorCallback(cb func(error)) Option
- func MaxReconnects(n int) Option
- func NATSOption(opt natsgo.Option) Option
- func Name(name string) Option
- func ReconnectCallback(cb func()) Option
- func ReconnectWait(d time.Duration) Option
- func Servers(urls ...string) Option
- func Timeout(d time.Duration) Option
- func Token(token string) Option
- func UserInfo(user, password string) Option
- type Subscription
Constants ¶
This section is empty.
Variables ¶
var ( // ErrConnectionClosed is returned when an operation is attempted on a closed // connection (NATS::IO::ConnectionClosedError). ErrConnectionClosed = errors.New("nats: connection closed") // ErrConnectionDraining is returned when publishing on a draining connection // (NATS::IO::ConnectionDrainingError). ErrConnectionDraining = errors.New("nats: connection draining") // ErrConnectionReconnecting is returned while the connection is reconnecting // (NATS::IO::ConnectionReconnectingError). ErrConnectionReconnecting = errors.New("nats: connection reconnecting") // ErrTimeout is returned when a request or flush does not complete in time // (NATS::IO::Timeout). ErrTimeout = errors.New("nats: timeout") // ErrNoResponders is returned by a request when no subscriber is listening on // the subject (NATS::IO::NoRespondersError). ErrNoResponders = errors.New("nats: no responders available for request") // ErrBadSubscription is returned for an invalid or already-removed // subscription (NATS::IO::BadSubscription). ErrBadSubscription = errors.New("nats: invalid subscription") // ErrBadSubject is returned for an empty or malformed subject // (NATS::IO::BadSubject). ErrBadSubject = errors.New("nats: invalid subject") // ErrNoServers is returned when no server is reachable at connect time // (NATS::IO::NoServersError). ErrNoServers = errors.New("nats: no servers available for connection") // ErrMaxPayload is returned when a message exceeds the server's max payload // (NATS::IO::MaxPayloadError). ErrMaxPayload = errors.New("nats: maximum payload exceeded") // ErrInvalidCallback is returned when a subscription is created without a // message-handler block. ErrInvalidCallback = errors.New("nats: invalid callback") // ErrNoReplySubject is returned by [Msg.Respond] when the message carries no // reply subject to answer on. ErrNoReplySubject = errors.New("nats: message has no reply subject") )
The error tree mirrors the Ruby client's exception classes. Upstream they are Ruby classes under NATS::Error / NATS::IO::*; here each is a sentinel value callers match with errors.Is. [mapError] translates the errors nats.go returns into these, so downstream code — and the Ruby host that raises the matching class — sees a stable set independent of the nats.go version.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a NATS connection, mirroring NATS::Client. It publishes and subscribes over a transport [conn] and does not own the socket itself — the dialer does. Construct one with Connect.
func Connect ¶
Connect opens a connection to a NATS server, mirroring NATS.connect. The transport is a real nats.go connection; configure it with Option values such as Servers, Name and UserInfo.
func (*Client) Close ¶
func (c *Client) Close()
Close closes the connection immediately, mirroring NATS::Client#close.
func (*Client) Drain ¶
Drain unsubscribes all subscriptions, flushes pending messages and closes the connection, mirroring NATS::Client#drain.
func (*Client) Flush ¶
Flush waits for the server to process all buffered messages, mirroring NATS::Client#flush.
func (*Client) FlushTimeout ¶
FlushTimeout is Client.Flush bounded by timeout, returning ErrTimeout if it does not complete in time.
func (*Client) IsClosed ¶
IsClosed reports whether the connection is closed, mirroring NATS::Client#closed?.
func (*Client) OnClose ¶
func (c *Client) OnClose(cb func())
OnClose registers a callback fired when the connection closes, mirroring NATS::Client#on_close.
func (*Client) OnDisconnect ¶
func (c *Client) OnDisconnect(cb func())
OnDisconnect registers a callback fired when the client disconnects, mirroring NATS::Client#on_disconnect.
func (*Client) OnError ¶
OnError registers a callback for asynchronous errors, mirroring NATS::Client#on_error.
func (*Client) OnReconnect ¶
func (c *Client) OnReconnect(cb func())
OnReconnect registers a callback fired after the client reconnects, mirroring NATS::Client#on_reconnect.
func (*Client) PublishMsg ¶
PublishMsg publishes a fully-formed Msg (carrying Reply and Header), mirroring NATS::Client#publish_msg.
func (*Client) PublishRequest ¶
PublishRequest publishes data to subject with reply set as the response subject, mirroring NATS::Client#publish(subject, data, reply:).
func (*Client) QueueSubscribe ¶
func (c *Client) QueueSubscribe(subject, queue string, cb func(*Msg)) (*Subscription, error)
QueueSubscribe registers a queue-group subscription: the server load-balances matching messages across members of queue, mirroring NATS::Client#subscribe(subject, queue:).
func (*Client) Request ¶
Request publishes data to subject and waits up to timeout for a single reply, mirroring NATS::Client#request. It returns ErrNoResponders if nobody is listening and ErrTimeout if no reply arrives in time.
func (*Client) RequestMsg ¶
RequestMsg is Client.Request for a pre-built Msg (carrying Header), mirroring NATS::Client#request with a message.
func (*Client) Subscribe ¶
func (c *Client) Subscribe(subject string, cb func(*Msg)) (*Subscription, error)
Subscribe registers interest in subject and delivers each matching message to cb, mirroring NATS::Client#subscribe(subject) { |msg| }.
func (*Client) Unsubscribe ¶
func (c *Client) Unsubscribe(sub *Subscription) error
Unsubscribe removes sub, mirroring NATS::Client#unsubscribe.
type Header ¶
Header carries a message's optional headers, mirroring NATS::Msg#headers — a case-preserving multimap of string keys to string values (the same shape as nats.go's Header and net/textproto's MIMEHeader). A nil Header is a valid empty header for reads.
type Msg ¶
type Msg struct {
// Subject the message was published to (or delivered on).
Subject string
// Reply is the subject a responder should answer on, if any.
Reply string
// Data is the message payload.
Data []byte
// Header holds optional headers.
Header Header
// Sub is the subscription that delivered this message (nil for messages the
// caller builds).
Sub *Subscription
// contains filtered or unexported fields
}
Msg is a NATS message, mirroring NATS::Msg. Subscribers receive one; publishers may build one for Client.PublishMsg to carry a Reply subject or Header.
func (*Msg) Respond ¶
Respond publishes data to the message's Reply subject, mirroring NATS::Msg#respond. It returns ErrNoReplySubject if the message has no reply subject and ErrConnectionClosed if it is not bound to a connection.
func (*Msg) RespondMsg ¶
RespondMsg publishes resp (with its Header) to the message's Reply subject, mirroring NATS::Msg#respond_msg.
type Option ¶
type Option func(*options)
Option configures a Connect call. The provided options mirror the gem's NATS.connect keyword arguments.
func ClosedCallback ¶
func ClosedCallback(cb func()) Option
ClosedCallback registers the on_close callback at connect time.
func DisconnectCallback ¶
func DisconnectCallback(cb func()) Option
DisconnectCallback registers the on_disconnect callback at connect time.
func ErrorCallback ¶
ErrorCallback registers the on_error callback at connect time.
func MaxReconnects ¶
MaxReconnects sets the reconnect attempt limit (NATS.connect max_reconnect_attempts:).
func NATSOption ¶
NATSOption threads a raw nats.go github.com/nats-io/nats.go.Option into the underlying connection — an escape hatch for transport features (TLS, JWT, in-process server) not surfaced by the gem-shaped options above.
func ReconnectCallback ¶
func ReconnectCallback(cb func()) Option
ReconnectCallback registers the on_reconnect callback at connect time.
func ReconnectWait ¶
ReconnectWait sets the delay between reconnect attempts (NATS.connect reconnect_time_wait:).
type Subscription ¶
type Subscription struct {
// Subject is the subscribed subject (may contain wildcards).
Subject string
// Queue is the queue group, or "" for a plain subscription.
Queue string
// contains filtered or unexported fields
}
Subscription is an interest registration, mirroring NATS::Subscription. It is returned by Client.Subscribe / Client.QueueSubscribe and delivers messages to the callback given there.
func (*Subscription) AutoUnsubscribe ¶
func (s *Subscription) AutoUnsubscribe(max int) error
AutoUnsubscribe removes the subscription after max more messages are delivered, mirroring the gem's subscribe(max:) auto-unsubscribe.
func (*Subscription) Drain ¶
func (s *Subscription) Drain() error
Drain removes the subscription after its buffered messages are processed, mirroring NATS::Subscription#drain.
func (*Subscription) Unsubscribe ¶
func (s *Subscription) Unsubscribe() error
Unsubscribe removes the subscription, mirroring NATS::Subscription#unsubscribe.
