Connect to a cluster somebody else runs¶
Most services should do this. If a NATS cluster already exists, importing nats/server pulls a
broker into your binary to reach a broker that is already running.
cli, err := client.Connect(ctx, gonats.ClientSettings{
URL: "nats://nats.internal:4222",
Name: "my-service",
}, credential)
That is the entire difference from the in-process case. No server import, no client.InProcess,
and everything that publishes or subscribes is unchanged.
The credential¶
The second argument is a gonats.CredentialSource — a function returning the token, resolved when
the connection is made rather than carried around as a string.
func credential(p *props.Props) gonats.CredentialSource {
return func(ctx context.Context) (string, error) {
return vcs.SomeEstateLadder(ctx) // env var name, keychain, literal
}
}
This module deliberately does not compose that ladder. Precedence is the application's decision, and a library that decides it is a second statement of something the estate already states once.
nil is accepted, and should only ever be passed for an in-process server with no authentication.
Anything reachable over a network wants a credential.
One target, or none¶
// Refused: nothing to connect to.
client.Connect(ctx, gonats.ClientSettings{}, nil)
// Refused: two different things.
client.Connect(ctx, gonats.ClientSettings{URL: "nats://..."}, cred, client.InProcess(srv))
Supplying both says two different things, and guessing which was meant is how a service ends up talking to a broker nobody thought it was talking to.
Reconnection¶
The default is to retry forever, two seconds apart. That is deliberate: a long-running service that gives up reconnecting has to be restarted by a person to recover from an outage it would otherwise have survived on its own.
Set MaxReconnects if your service genuinely should die instead.