• Stars
    star
    5,119
  • Rank 7,711 (Top 0.2 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created over 11 years ago
  • Updated 21 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang client for NATS, the cloud native messaging system.

NATS - Go Client

A Go client for the NATS messaging system.

License Apache 2 Go Report Card Build Status GoDoc Coverage Status

Check out NATS by example - An evolving collection of runnable, cross-client reference examples for NATS.

Installation

# Go client
go get github.com/nats-io/nats.go/

# Server
go get github.com/nats-io/nats-server

When using or transitioning to Go modules support:

# Go client latest or explicit version
go get github.com/nats-io/nats.go/@latest
go get github.com/nats-io/nats.go/@v1.34.1

# For latest NATS Server, add /v2 at the end
go get github.com/nats-io/nats-server/v2

# NATS Server v1 is installed otherwise
# go get github.com/nats-io/nats-server

Basic Usage

import "github.com/nats-io/nats.go"

// Connect to a server
nc, _ := nats.Connect(nats.DefaultURL)

// Simple Publisher
nc.Publish("foo", []byte("Hello World"))

// Simple Async Subscriber
nc.Subscribe("foo", func(m *nats.Msg) {
    fmt.Printf("Received a message: %s\n", string(m.Data))
})

// Responding to a request message
nc.Subscribe("request", func(m *nats.Msg) {
    m.Respond([]byte("answer is 42"))
})

// Simple Sync Subscriber
sub, err := nc.SubscribeSync("foo")
m, err := sub.NextMsg(timeout)

// Channel Subscriber
ch := make(chan *nats.Msg, 64)
sub, err := nc.ChanSubscribe("foo", ch)
msg := <- ch

// Unsubscribe
sub.Unsubscribe()

// Drain
sub.Drain()

// Requests
msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond)

// Replies
nc.Subscribe("help", func(m *nats.Msg) {
    nc.Publish(m.Reply, []byte("I can help!"))
})

// Drain connection (Preferred for responders)
// Close() not needed if this is called.
nc.Drain()

// Close connection
nc.Close()

JetStream

JetStream is the built-in NATS persistence system. nats.go provides a built-in API enabling both managing JetStream assets as well as publishing/consuming persistent messages.

Basic usage

// connect to nats server
nc, _ := nats.Connect(nats.DefaultURL)

// create jetstream context from nats connection
js, _ := jetstream.New(nc)

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

// get existing stream handle
stream, _ := js.Stream(ctx, "foo")

// retrieve consumer handle from a stream
cons, _ := stream.Consumer(ctx, "cons")

// consume messages from the consumer in callback
cc, _ := cons.Consume(func(msg jetstream.Msg) {
    fmt.Println("Received jetstream message: ", string(msg.Data()))
    msg.Ack()
})
defer cc.Stop()

To find more information on nats.go JetStream API, visit jetstream/README.md

The current JetStream API replaces the legacy JetStream API

Service API

The service API (micro) allows you to easily build NATS services The services API is currently in beta release.

Encoded Connections

nc, _ := nats.Connect(nats.DefaultURL)
c, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
defer c.Close()

// Simple Publisher
c.Publish("foo", "Hello World")

// Simple Async Subscriber
c.Subscribe("foo", func(s string) {
    fmt.Printf("Received a message: %s\n", s)
})

// EncodedConn can Publish any raw Go type using the registered Encoder
type person struct {
     Name     string
     Address  string
     Age      int
}

// Go type Subscriber
c.Subscribe("hello", func(p *person) {
    fmt.Printf("Received a person: %+v\n", p)
})

me := &person{Name: "derek", Age: 22, Address: "140 New Montgomery Street, San Francisco, CA"}

// Go type Publisher
c.Publish("hello", me)

// Unsubscribe
sub, err := c.Subscribe("foo", nil)
// ...
sub.Unsubscribe()

// Requests
var response string
err = c.Request("help", "help me", &response, 10*time.Millisecond)
if err != nil {
    fmt.Printf("Request failed: %v\n", err)
}

// Replying
c.Subscribe("help", func(subj, reply string, msg string) {
    c.Publish(reply, "I can help!")
})

// Close connection
c.Close();

New Authentication (Nkeys and User Credentials)

This requires server with version >= 2.0.0

NATS servers have a new security and authentication mechanism to authenticate with user credentials and Nkeys. The simplest form is to use the helper method UserCredentials(credsFilepath).

nc, err := nats.Connect(url, nats.UserCredentials("user.creds"))

The helper methods creates two callback handlers to present the user JWT and sign the nonce challenge from the server. The core client library never has direct access to your private key and simply performs the callback for signing the server challenge. The helper will load and wipe and erase memory it uses for each connect or reconnect.

The helper also can take two entries, one for the JWT and one for the NKey seed file.

nc, err := nats.Connect(url, nats.UserCredentials("user.jwt", "user.nk"))

You can also set the callback handlers directly and manage challenge signing directly.

nc, err := nats.Connect(url, nats.UserJWT(jwtCB, sigCB))

Bare Nkeys are also supported. The nkey seed should be in a read only file, e.g. seed.txt

> cat seed.txt
# This is my seed nkey!
SUAGMJH5XLGZKQQWAWKRZJIGMOU4HPFUYLXJMXOO5NLFEO2OOQJ5LPRDPM

This is a helper function which will load and decode and do the proper signing for the server nonce. It will clear memory in between invocations. You can choose to use the low level option and provide the public key and a signature callback on your own.

opt, err := nats.NkeyOptionFromSeed("seed.txt")
nc, err := nats.Connect(serverUrl, opt)

// Direct
nc, err := nats.Connect(serverUrl, nats.Nkey(pubNkey, sigCB))

TLS

// tls as a scheme will enable secure connections by default. This will also verify the server name.
nc, err := nats.Connect("tls://nats.demo.io:4443")

// If you are using a self-signed certificate, you need to have a tls.Config with RootCAs setup.
// We provide a helper method to make this case easier.
nc, err = nats.Connect("tls://localhost:4443", nats.RootCAs("./configs/certs/ca.pem"))

// If the server requires client certificate, there is an helper function for that too:
cert := nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem")
nc, err = nats.Connect("tls://localhost:4443", cert)

// You can also supply a complete tls.Config

certFile := "./configs/certs/client-cert.pem"
keyFile := "./configs/certs/client-key.pem"
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
    t.Fatalf("error parsing X509 certificate/key pair: %v", err)
}

config := &tls.Config{
    ServerName: 	opts.Host,
    Certificates: 	[]tls.Certificate{cert},
    RootCAs:    	pool,
    MinVersion: 	tls.VersionTLS12,
}

nc, err = nats.Connect("nats://localhost:4443", nats.Secure(config))
if err != nil {
	t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
}

Using Go Channels (netchan)

nc, _ := nats.Connect(nats.DefaultURL)
ec, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
defer ec.Close()

type person struct {
     Name     string
     Address  string
     Age      int
}

recvCh := make(chan *person)
ec.BindRecvChan("hello", recvCh)

sendCh := make(chan *person)
ec.BindSendChan("hello", sendCh)

me := &person{Name: "derek", Age: 22, Address: "140 New Montgomery Street"}

// Send via Go channels
sendCh <- me

// Receive via Go channels
who := <- recvCh

Wildcard Subscriptions

// "*" matches any token, at any level of the subject.
nc.Subscribe("foo.*.baz", func(m *Msg) {
    fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data));
})

nc.Subscribe("foo.bar.*", func(m *Msg) {
    fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data));
})

// ">" matches any length of the tail of a subject, and can only be the last token
// E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22'
nc.Subscribe("foo.>", func(m *Msg) {
    fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data));
})

// Matches all of the above
nc.Publish("foo.bar.baz", []byte("Hello World"))

Queue Groups

// All subscriptions with the same queue name will form a queue group.
// Each message will be delivered to only one subscriber per queue group,
// using queuing semantics. You can have as many queue groups as you wish.
// Normal subscribers will continue to work as expected.

nc.QueueSubscribe("foo", "job_workers", func(_ *Msg) {
  received += 1;
})

Advanced Usage

// Normally, the library will return an error when trying to connect and
// there is no server running. The RetryOnFailedConnect option will set
// the connection in reconnecting state if it failed to connect right away.
nc, err := nats.Connect(nats.DefaultURL,
    nats.RetryOnFailedConnect(true),
    nats.MaxReconnects(10),
    nats.ReconnectWait(time.Second),
    nats.ReconnectHandler(func(_ *nats.Conn) {
        // Note that this will be invoked for the first asynchronous connect.
    }))
if err != nil {
    // Should not return an error even if it can't connect, but you still
    // need to check in case there are some configuration errors.
}

// Flush connection to server, returns when all messages have been processed.
nc.Flush()
fmt.Println("All clear!")

// FlushTimeout specifies a timeout value as well.
err := nc.FlushTimeout(1*time.Second)
if err != nil {
    fmt.Println("All clear!")
} else {
    fmt.Println("Flushed timed out!")
}

// Auto-unsubscribe after MAX_WANTED messages received
const MAX_WANTED = 10
sub, err := nc.Subscribe("foo")
sub.AutoUnsubscribe(MAX_WANTED)

// Multiple connections
nc1 := nats.Connect("nats://host1:4222")
nc2 := nats.Connect("nats://host2:4222")

nc1.Subscribe("foo", func(m *Msg) {
    fmt.Printf("Received a message: %s\n", string(m.Data))
})

nc2.Publish("foo", []byte("Hello World!"));

Clustered Usage

var servers = "nats://localhost:1222, nats://localhost:1223, nats://localhost:1224"

nc, err := nats.Connect(servers)

// Optionally set ReconnectWait and MaxReconnect attempts.
// This example means 10 seconds total per backend.
nc, err = nats.Connect(servers, nats.MaxReconnects(5), nats.ReconnectWait(2 * time.Second))

// You can also add some jitter for the reconnection.
// This call will add up to 500 milliseconds for non TLS connections and 2 seconds for TLS connections.
// If not specified, the library defaults to 100 milliseconds and 1 second, respectively.
nc, err = nats.Connect(servers, nats.ReconnectJitter(500*time.Millisecond, 2*time.Second))

// You can also specify a custom reconnect delay handler. If set, the library will invoke it when it has tried
// all URLs in its list. The value returned will be used as the total sleep time, so add your own jitter.
// The library will pass the number of times it went through the whole list.
nc, err = nats.Connect(servers, nats.CustomReconnectDelay(func(attempts int) time.Duration {
    return someBackoffFunction(attempts)
}))

// Optionally disable randomization of the server pool
nc, err = nats.Connect(servers, nats.DontRandomize())

// Setup callbacks to be notified on disconnects, reconnects and connection closed.
nc, err = nats.Connect(servers,
	nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
		fmt.Printf("Got disconnected! Reason: %q\n", err)
	}),
	nats.ReconnectHandler(func(nc *nats.Conn) {
		fmt.Printf("Got reconnected to %v!\n", nc.ConnectedUrl())
	}),
	nats.ClosedHandler(func(nc *nats.Conn) {
		fmt.Printf("Connection closed. Reason: %q\n", nc.LastError())
	})
)

// When connecting to a mesh of servers with auto-discovery capabilities,
// you may need to provide a username/password or token in order to connect
// to any server in that mesh when authentication is required.
// Instead of providing the credentials in the initial URL, you will use
// new option setters:
nc, err = nats.Connect("nats://localhost:4222", nats.UserInfo("foo", "bar"))

// For token based authentication:
nc, err = nats.Connect("nats://localhost:4222", nats.Token("S3cretT0ken"))

// You can even pass the two at the same time in case one of the server
// in the mesh requires token instead of user name and password.
nc, err = nats.Connect("nats://localhost:4222",
    nats.UserInfo("foo", "bar"),
    nats.Token("S3cretT0ken"))

// Note that if credentials are specified in the initial URLs, they take
// precedence on the credentials specified through the options.
// For instance, in the connect call below, the client library will use
// the user "my" and password "pwd" to connect to localhost:4222, however,
// it will use username "foo" and password "bar" when (re)connecting to
// a different server URL that it got as part of the auto-discovery.
nc, err = nats.Connect("nats://my:pwd@localhost:4222", nats.UserInfo("foo", "bar"))

Context support (+Go 1.7)

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

nc, err := nats.Connect(nats.DefaultURL)

// Request with context
msg, err := nc.RequestWithContext(ctx, "foo", []byte("bar"))

// Synchronous subscriber with context
sub, err := nc.SubscribeSync("foo")
msg, err := sub.NextMsgWithContext(ctx)

// Encoded Request with context
c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
type request struct {
	Message string `json:"message"`
}
type response struct {
	Code int `json:"code"`
}
req := &request{Message: "Hello"}
resp := &response{}
err := c.RequestWithContext(ctx, "foo", req, resp)

Backwards compatibility

In the development of nats.go, we are committed to maintaining backward compatibility and ensuring a stable and reliable experience for all users. In general, we follow the standard go compatibility guidelines. However, it's important to clarify our stance on certain types of changes:

  • Expanding structures: Adding new fields to structs is not considered a breaking change.

  • Adding methods to exported interfaces: Extending public interfaces with new methods is also not viewed as a breaking change within the context of this project. It is important to note that no unexported methods will be added to interfaces allowing users to implement them.

Additionally, this library always supports at least 2 latest minor Go versions. For example, if the latest Go version is 1.22, the library will support Go 1.21 and 1.22.

License

Unless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.

FOSSA Status

More Repositories

1

nats-server

High-Performance server for NATS.io, the cloud and edge native messaging system.
Go
14,523
star
2

nats-streaming-server

NATS Streaming System Server
Go
2,495
star
3

nats.js

Node.js client for NATS, the cloud native messaging system.
JavaScript
1,477
star
4

nats.rs

Rust client for NATS, the cloud native messaging system.
Rust
933
star
5

nats.rb

Ruby client for NATS, the cloud native messaging system.
Ruby
880
star
6

nats.py

Python3 client for NATS
Python
797
star
7

stan.go

NATS Streaming System
Go
704
star
8

nats.net

The official C# Client for NATS
C#
636
star
9

nats-operator

NATS Operator
Go
569
star
10

nats.java

Java client for NATS
Java
538
star
11

jetstream

JetStream Utilities
Dockerfile
452
star
12

natscli

The NATS Command Line Interface
Go
414
star
13

k8s

NATS on Kubernetes with Helm Charts
Go
402
star
14

nats.c

A C client for NATS
C
367
star
15

nuid

NATS Unique Identifiers
Go
357
star
16

prometheus-nats-exporter

A Prometheus exporter for NATS metrics
Go
344
star
17

nats-top

A top-like tool for monitoring NATS servers.
Go
331
star
18

stan.js

Node.js client for NATS Streaming
JavaScript
293
star
19

nats.ws

WebSocket NATS
JavaScript
290
star
20

nats-surveyor

NATS Monitoring, Simplified.
Go
194
star
21

nats.ex

Elixir client for NATS, the cloud native messaging system. https://nats.io
Elixir
189
star
22

nats.ts

TypeScript Node.js client for NATS, the cloud native messaging system
TypeScript
178
star
23

graft

A RAFT Election implementation in Go.
Go
176
star
24

nats-streaming-operator

NATS Streaming Operator
Go
172
star
25

nats.net.v2

Full Async C# / .NET client for NATS
C#
170
star
26

nats-architecture-and-design

Architecture and Design Docs
Go
164
star
27

nats.deno

Deno client for NATS, the cloud native messaging system
TypeScript
149
star
28

nack

NATS Controllers for Kubernetes (NACK)
Go
139
star
29

stan.net

The official NATS .NET C# Streaming Client
C#
137
star
30

jsm.go

JetStream Management Library for Golang
Go
132
star
31

nats-docker

Official Docker image for the NATS server
Dockerfile
123
star
32

nkeys

NATS Keys
Go
120
star
33

nats-pure.rb

Ruby client for NATS, the cloud native messaging system.
Ruby
117
star
34

nats-kafka

NATS to Kafka Bridging
Go
116
star
35

stan.py

Python Asyncio NATS Streaming Client
Python
113
star
36

nats.zig

Zig Client for NATS
109
star
37

go-nats-examples

Single repository for go-nats example code. This includes all documentation examples and any common message pattern examples.
Go
108
star
38

nginx-nats

NGINX client module for NATS, the cloud native messaging system.
C
105
star
39

nats.docs

NATS.io Documentation on Gitbook
HTML
103
star
40

nats-box

A container with NATS utilities
HCL
96
star
41

stan.java

NATS Streaming Java Client
Java
93
star
42

not.go

A reference for distributed tracing with the NATS Go client.
Go
91
star
43

nats-site

Website content for https://nats.io. For technical issues with NATS products, please log an issue in the proper repository.
Markdown
87
star
44

jparse

Small, Fast, Compliant JSON parser that uses events parsing and index overlay
Java
86
star
45

nsc

Tool for creating nkey/jwt based configurations
Go
83
star
46

elixir-nats

Elixir NATS client
Elixir
75
star
47

nats-account-server

A simple HTTP/NATS server to host JWTs for nats-server 2.0 account authentication.
Go
73
star
48

jwt

JWT tokens signed using NKeys for Ed25519 for the NATS ecosystem.
Go
68
star
49

nats.py2

A Tornado based Python 2 client for NATS
Python
62
star
50

nats-general

General NATS Information
61
star
51

spring-nats

A Spring Cloud Stream Binder for NATS
Java
57
star
52

terraform-provider-jetstream

Terraform Provider to manage NATS JetStream
Go
54
star
53

nats.cr

Crystal client for NATS
Crystal
44
star
54

nats-streaming-docker

Official Docker image for the NATS Streaming server
Python
44
star
55

nats-connector-framework

A pluggable service to bridge NATS with other technologies
Java
32
star
56

nats-rest-config-proxy

NATS REST Configuration Proxy
Go
32
star
57

demo-minio-nats

Demo of syncing across clouds with minio
Go
27
star
58

java-nats-examples

Repo for java-nats-examples
Java
26
star
59

asyncio-nats-examples

Repo for Python Asyncio examples
Python
24
star
60

stan.rb

Ruby NATS Streaming Client
Ruby
21
star
61

nats-mq

Simple bridge between NATS streaming and MQ Series
Go
21
star
62

jetstream-leaf-nodes-demo

Go
20
star
63

go-nats

[ARCHIVED] Golang client for NATS, the cloud native messaging system.
Go
20
star
64

nats-on-a-log

Raft log replication using NATS.
Go
20
star
65

nats-replicator

Bridge to replicate NATS Subjects or Channels to NATS Subject or Channels
Go
19
star
66

nkeys.js

NKeys for JavaScript - Node.js, Browsers, and Deno.
TypeScript
18
star
67

latency-tests

Latency and Throughput Test Framework
HCL
14
star
68

nats-jms-bridge

NATS to JMS Bridge for request/reply
Java
12
star
69

nats-connector-redis

A Redis Publish/Subscribe NATS Connector
Java
12
star
70

node-nuid

A Node.js implementation of NUID
JavaScript
10
star
71

nats-java-vertx-client

Java
10
star
72

nats.swift

Swift client for NATS, the cloud native messaging system.
Swift
10
star
73

sublist

History of the original sublist
Go
9
star
74

nkeys.py

NATS Keys for Python
Python
8
star
75

nats-siddhi-demo

A NATS with Siddhi Event Processing Reference Architecture
8
star
76

node-nats-examples

Documentation samples for node-nats
JavaScript
8
star
77

jwt.js

JWT tokens signed using nkeys for Ed25519 for the NATS JavaScript ecosystem
TypeScript
7
star
78

jetstream-gh-action

Collection of JetStream related Actions for GitHub Actions
Go
7
star
79

kubecon2020

Go
7
star
80

nats-spark-connector

Scala
7
star
81

java-nats-server-runner

Run the Nats Server From your Java code.
Java
6
star
82

kotlin-nats-examples

Repo for Kotlin Nats examples.
Kotlin
6
star
83

js-nuid

TypeScript
6
star
84

ts-nats-examples

typescript nats examples
TypeScript
5
star
85

go-nats-streaming

[ARCHIVED] NATS Streaming System
Go
5
star
86

integration-tests

Repository for integration test suites of any language
Java
5
star
87

homebrew-nats-tools

Repository hosting homebrew taps for nats-io tools
Ruby
5
star
88

ts-nkeys

A public-key signature system based on Ed25519 for the NATS ecosystem in typescript for ts-nats and node-nats
TypeScript
4
star
89

nats-steampipe-plugin

Example steampipe plugin for NATS
Go
4
star
90

nkeys.rb

NATS Keys for Ruby
Ruby
4
star
91

advisories

Advisories related to the NATS project
HTML
3
star
92

kinesis-bridge

Bridge Amazon Kinesis to NATS streams.
Go
3
star
93

not.java

A reference for distributed tracing with the NATS Java client.
Java
2
star
94

deploy

Deployment for NATS
Ruby
2
star
95

nats.c.deps

C
2
star
96

stan2js

NATS Streaming to JetStream data migration tool.
Go
2
star
97

netlify-slack

Trivial redirector website
1
star
98

cliprompts

cli prompt utils
Go
1
star
99

ruby-nats-examples

Repo for Ruby Examples
Ruby
1
star
100

nats-mendix

CSS
1
star