Skip to content

Connect to a NATS server

Build the backend, then hand it to messaging.New. The constructor acquires nothing; the connection is made when the bus starts.

import (
    "log/slog"

    gonats "gitlab.com/phpboyscout/go/nats"

    "gitlab.com/phpboyscout/go/messaging"
    nats "gitlab.com/phpboyscout/go/messaging-nats"
)

backend := nats.Core(nats.Settings{
    Client: gonats.ClientSettings{Name: "orders", URL: "nats://nats.internal:4222"},
    Credentials: gonats.StaticCredential(token),
    Logger: slog.Default(),
})

bus, err := messaging.New(backend, messaging.Settings{Subscriptions: specs})

nats.JetStream takes JetStreamSettings, which adds Stream; see Bind to a stream.

Set a name and a logger

Set Client.Name: it names the connection in the server's monitoring, and an unnamed connection is a poor thing to find in a slow-consumer report.

Set Logger. Left nil it discards everything, including the warnings that tell you a message could not be read.

Give it credentials

Credentials is a gonats.CredentialSource, a function that yields a token when the connection is made, so the secret is resolved at connect time. gonats.StaticCredential(token) returns a source for a token already in hand. Resolve it by whatever route your application uses and pass the function in.

What Open does

The bus calls Open from Start. For each backend it:

  1. builds the client from Client, Credentials and Options, with Logger;
  2. starts the client and waits until the connection is ready, stopping it if the wait fails;
  3. for JetStream, takes the JetStream context and binds the stream.

A failure at any step is wrapped as listed in Errors.

Reconnection

By default the client retries for ever, two seconds apart. NATS restores subscriptions when the server returns, and a Core subscription stays alive meanwhile. To make a dropped connection end the subscription instead, give MaxReconnects a finite value:

Client: gonats.ClientSettings{URL: url, MaxReconnects: gonats.Reconnects(5)}

When the client gives up, the connection reaches CLOSED and each Core subscription ends with messaging-nats: the connection closed.

Connect to an embedded server

Options takes client.InProcess(server) to connect to a go/nats embedded server in the same process, with Client.URL left empty. The tutorial does this.

Close

Closing the session retires every source, then closes the client, which drains instead of dropping. A deadline-free context gets go/nats's default drain timeout of 10 seconds.