Skip to content

A Go package for connecting to and interacting with a NATS server.

License

Notifications You must be signed in to change notification settings

osapi-io/nats-client

release codecov go report card license build powered by conventional commits nats built with just gitHub commit activity

NATS Client

A Go package for connecting to and interacting with a NATS server.

Usage

package main
import (
"context"
"log/slog"
"os"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"github.com/osapi-io/nats-client/pkg/client"
)
func main() {
logger := slog.Default()
opts := &client.Options{
Host: "localhost",
Port: 4222,
Auth: client.AuthOptions{
AuthType: client.NoAuth,
},
}
c := client.New(logger, opts)
if err := c.Connect(); err != nil {
logger.Error("failed to connect", "error", err)
os.Exit(1)
}
defer c.NC.Close()
logger.Info("connected", "url", c.NC.ConnectedUrl())
streamOpts := &client.StreamConfig{
StreamConfig: &nats.StreamConfig{
Name: "STREAM2",
Subjects: []string{"stream2.*"},
Storage: nats.FileStorage,
Replicas: 1,
},
Consumers: []*client.ConsumerConfig{
{
ConsumerConfig: &jetstream.ConsumerConfig{
Durable: "consumer3",
AckPolicy: jetstream.AckExplicitPolicy,
MaxDeliver: 5,
AckWait: 30 * time.Second,
},
},
{
ConsumerConfig: &jetstream.ConsumerConfig{
Durable: "consumer4",
AckPolicy: jetstream.AckExplicitPolicy,
MaxDeliver: 5,
AckWait: 30 * time.Second,
},
},
},
}
ctx := context.Background()
if err := c.CreateOrUpdateJetStream(ctx, streamOpts); err != nil {
logger.Error("failed setting up jetstream", "error", err)
os.Exit(1)
}
}

See the examples section for additional use cases.

Documentation

See the generated documentation for details on available packages and functions.

Contributing

See the Development guide for prerequisites, setup, and conventions. See the Contributing guide before submitting a PR.

License

The MIT License.