| 1 |
# NATS - Go Client |
| 2 |
A [Go](http://golang.org) client for the [NATS messaging system](https://nats.io). |
| 3 |
|
| 4 |
[![License Apache 2][License-Image]][License-Url] [![Go Report Card][ReportCard-Image]][ReportCard-Url] [![Build Status][Build-Status-Image]][Build-Status-Url] [![GoDoc][GoDoc-Image]][GoDoc-Url] [![Coverage Status][Coverage-image]][Coverage-Url] |
| 5 |
|
| 6 |
[License-Url]: https://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
[License-Image]: https://img.shields.io/badge/License-Apache2-blue.svg |
| 8 |
[ReportCard-Url]: https://goreportcard.com/report/github.com/nats-io/nats.go |
| 9 |
[ReportCard-Image]: https://goreportcard.com/badge/github.com/nats-io/nats.go |
| 10 |
[Build-Status-Url]: https://github.com/nats-io/nats.go/actions/workflows/ci.yaml?query=event%3Arelease |
| 11 |
[Build-Status-Image]: https://github.com/nats-io/nats.go/actions/workflows/ci.yaml/badge.svg?event=release |
| 12 |
[GoDoc-Url]: https://pkg.go.dev/github.com/nats-io/nats.go |
| 13 |
[GoDoc-Image]: https://img.shields.io/badge/GoDoc-reference-007d9c |
| 14 |
[Coverage-Url]: https://coveralls.io/r/nats-io/nats.go?branch=main |
| 15 |
[Coverage-image]: https://coveralls.io/repos/github/nats-io/nats.go/badge.svg?branch=main |
| 16 |
|
| 17 |
**Check out [NATS by example](https://natsbyexample.com) - An evolving collection of runnable, cross-client reference examples for NATS.** |
| 18 |
|
| 19 |
## Installation |
| 20 |
|
| 21 |
```bash |
| 22 |
# To get the latest released Go client: |
| 23 |
go get github.com/nats-io/nats.go@latest |
| 24 |
|
| 25 |
# To get a specific version: |
| 26 |
go get github.com/nats-io/[email protected] |
| 27 |
|
| 28 |
# Note that the latest major version for NATS Server is v2: |
| 29 |
go get github.com/nats-io/nats-server/v2@latest |
| 30 |
``` |
| 31 |
|
| 32 |
## Basic Usage |
| 33 |
|
| 34 |
```go |
| 35 |
import "github.com/nats-io/nats.go" |
| 36 |
|
| 37 |
// Connect to a server |
| 38 |
nc, _ := nats.Connect(nats.DefaultURL) |
| 39 |
|
| 40 |
// Simple Publisher |
| 41 |
nc.Publish("foo", []byte("Hello World")) |
| 42 |
|
| 43 |
// Simple Async Subscriber |
| 44 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 45 |
fmt.Printf("Received a message: %s\n", string(m.Data)) |
| 46 |
}) |
| 47 |
|
| 48 |
// Responding to a request message |
| 49 |
nc.Subscribe("request", func(m *nats.Msg) { |
| 50 |
m.Respond([]byte("answer is 42")) |
| 51 |
}) |
| 52 |
|
| 53 |
// Simple Sync Subscriber |
| 54 |
sub, err := nc.SubscribeSync("foo") |
| 55 |
m, err := sub.NextMsg(timeout) |
| 56 |
|
| 57 |
// Channel Subscriber |
| 58 |
ch := make(chan *nats.Msg, 64) |
| 59 |
sub, err := nc.ChanSubscribe("foo", ch) |
| 60 |
msg := <- ch |
| 61 |
|
| 62 |
// Unsubscribe |
| 63 |
sub.Unsubscribe() |
| 64 |
|
| 65 |
// Drain |
| 66 |
sub.Drain() |
| 67 |
|
| 68 |
// Requests |
| 69 |
msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond) |
| 70 |
|
| 71 |
// Replies |
| 72 |
nc.Subscribe("help", func(m *nats.Msg) { |
| 73 |
nc.Publish(m.Reply, []byte("I can help!")) |
| 74 |
}) |
| 75 |
|
| 76 |
// Drain connection (Preferred for responders) |
| 77 |
// Close() not needed if this is called. |
| 78 |
nc.Drain() |
| 79 |
|
| 80 |
// Close connection |
| 81 |
nc.Close() |
| 82 |
``` |
| 83 |
|
| 84 |
## JetStream |
| 85 |
[](https://pkg.go.dev/github.com/nats-io/nats.go/jetstream) |
| 86 |
|
| 87 |
JetStream is the built-in NATS persistence system. `nats.go` provides a built-in |
| 88 |
API enabling both managing JetStream assets as well as publishing/consuming |
| 89 |
persistent messages. |
| 90 |
|
| 91 |
|
| 92 |
### Basic usage |
| 93 |
|
| 94 |
```go |
| 95 |
// connect to nats server |
| 96 |
nc, _ := nats.Connect(nats.DefaultURL) |
| 97 |
|
| 98 |
// create jetstream context from nats connection |
| 99 |
js, _ := jetstream.New(nc) |
| 100 |
|
| 101 |
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 102 |
defer cancel() |
| 103 |
|
| 104 |
// get existing stream handle |
| 105 |
stream, _ := js.Stream(ctx, "foo") |
| 106 |
|
| 107 |
// retrieve consumer handle from a stream |
| 108 |
cons, _ := stream.Consumer(ctx, "cons") |
| 109 |
|
| 110 |
// consume messages from the consumer in callback |
| 111 |
cc, _ := cons.Consume(func(msg jetstream.Msg) { |
| 112 |
fmt.Println("Received jetstream message: ", string(msg.Data())) |
| 113 |
msg.Ack() |
| 114 |
}) |
| 115 |
defer cc.Stop() |
| 116 |
``` |
| 117 |
|
| 118 |
To find more information on `nats.go` JetStream API, visit |
| 119 |
[`jetstream/README.md`](jetstream/README.md) |
| 120 |
|
| 121 |
> The current JetStream API replaces the [legacy JetStream API](legacy_jetstream.md) |
| 122 |
|
| 123 |
## Service API |
| 124 |
|
| 125 |
The service API (`micro`) allows you to [easily build NATS services](micro/README.md) The |
| 126 |
services API is currently in beta release. |
| 127 |
|
| 128 |
## New Authentication (Nkeys and User Credentials) |
| 129 |
This requires server with version >= 2.0.0 |
| 130 |
|
| 131 |
NATS servers have a new security and authentication mechanism to authenticate with user credentials and Nkeys. |
| 132 |
The simplest form is to use the helper method UserCredentials(credsFilepath). |
| 133 |
```go |
| 134 |
nc, err := nats.Connect(url, nats.UserCredentials("user.creds")) |
| 135 |
``` |
| 136 |
|
| 137 |
The helper method creates two callback handlers to present the user JWT and sign the nonce challenge from the server. |
| 138 |
The core client library never has direct access to your private key and simply performs the callback for signing the server challenge. |
| 139 |
The helper will load and wipe and erase memory it uses for each connect or reconnect. |
| 140 |
|
| 141 |
The helper also can take two entries, one for the JWT and one for the NKey seed file. |
| 142 |
```go |
| 143 |
nc, err := nats.Connect(url, nats.UserCredentials("user.jwt", "user.nk")) |
| 144 |
``` |
| 145 |
|
| 146 |
You can also set the callback handlers directly and manage challenge signing directly. |
| 147 |
```go |
| 148 |
nc, err := nats.Connect(url, nats.UserJWT(jwtCB, sigCB)) |
| 149 |
``` |
| 150 |
|
| 151 |
Bare Nkeys are also supported. The nkey seed should be in a read only file, e.g. seed.txt |
| 152 |
```bash |
| 153 |
> cat seed.txt |
| 154 |
# This is my seed nkey! |
| 155 |
SUAGMJH5XLGZKQQWAWKRZJIGMOU4HPFUYLXJMXOO5NLFEO2OOQJ5LPRDPM |
| 156 |
``` |
| 157 |
|
| 158 |
This is a helper function which will load and decode and do the proper signing for the server nonce. |
| 159 |
It will clear memory in between invocations. |
| 160 |
You can choose to use the low level option and provide the public key and a signature callback on your own. |
| 161 |
|
| 162 |
```go |
| 163 |
opt, err := nats.NkeyOptionFromSeed("seed.txt") |
| 164 |
nc, err := nats.Connect(serverUrl, opt) |
| 165 |
|
| 166 |
// Direct |
| 167 |
nc, err := nats.Connect(serverUrl, nats.Nkey(pubNkey, sigCB)) |
| 168 |
``` |
| 169 |
|
| 170 |
## TLS |
| 171 |
|
| 172 |
```go |
| 173 |
// tls as a scheme will enable secure connections by default. This will also verify the server name. |
| 174 |
nc, err := nats.Connect("tls://nats.demo.io:4443") |
| 175 |
|
| 176 |
// If you are using a self-signed certificate, you need to have a tls.Config with RootCAs setup. |
| 177 |
// We provide a helper method to make this case easier. |
| 178 |
nc, err = nats.Connect("tls://localhost:4443", nats.RootCAs("./configs/certs/ca.pem")) |
| 179 |
|
| 180 |
// If the server requires client certificate, there is a helper function for that too: |
| 181 |
cert := nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem") |
| 182 |
nc, err = nats.Connect("tls://localhost:4443", cert) |
| 183 |
|
| 184 |
// You can also supply a complete tls.Config |
| 185 |
|
| 186 |
certFile := "./configs/certs/client-cert.pem" |
| 187 |
keyFile := "./configs/certs/client-key.pem" |
| 188 |
cert, err := tls.LoadX509KeyPair(certFile, keyFile) |
| 189 |
if err != nil { |
| 190 |
t.Fatalf("error parsing X509 certificate/key pair: %v", err) |
| 191 |
} |
| 192 |
|
| 193 |
config := &tls.Config{ |
| 194 |
ServerName: opts.Host, |
| 195 |
Certificates: []tls.Certificate{cert}, |
| 196 |
RootCAs: pool, |
| 197 |
MinVersion: tls.VersionTLS12, |
| 198 |
} |
| 199 |
|
| 200 |
nc, err = nats.Connect("nats://localhost:4443", nats.Secure(config)) |
| 201 |
if err != nil { |
| 202 |
t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err) |
| 203 |
} |
| 204 |
|
| 205 |
``` |
| 206 |
|
| 207 |
## Wildcard Subscriptions |
| 208 |
|
| 209 |
```go |
| 210 |
|
| 211 |
// "*" matches any token, at any level of the subject. |
| 212 |
nc.Subscribe("foo.*.baz", func(m *Msg) { |
| 213 |
fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)) |
| 214 |
}) |
| 215 |
|
| 216 |
nc.Subscribe("foo.bar.*", func(m *Msg) { |
| 217 |
fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)) |
| 218 |
}) |
| 219 |
|
| 220 |
// ">" matches any length of the tail of a subject, and can only be the last token |
| 221 |
// E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22' |
| 222 |
nc.Subscribe("foo.>", func(m *Msg) { |
| 223 |
fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)) |
| 224 |
}) |
| 225 |
|
| 226 |
// Matches all of the above |
| 227 |
nc.Publish("foo.bar.baz", []byte("Hello World")) |
| 228 |
|
| 229 |
``` |
| 230 |
|
| 231 |
## Queue Groups |
| 232 |
|
| 233 |
```go |
| 234 |
// All subscriptions with the same queue name will form a queue group. |
| 235 |
// Each message will be delivered to only one subscriber per queue group, |
| 236 |
// using queuing semantics. You can have as many queue groups as you wish. |
| 237 |
// Normal subscribers will continue to work as expected. |
| 238 |
|
| 239 |
nc.QueueSubscribe("foo", "job_workers", func(_ *Msg) { |
| 240 |
received += 1 |
| 241 |
}) |
| 242 |
``` |
| 243 |
|
| 244 |
## Advanced Usage |
| 245 |
|
| 246 |
```go |
| 247 |
|
| 248 |
// Normally, the library will return an error when trying to connect and |
| 249 |
// there is no server running. The RetryOnFailedConnect option will set |
| 250 |
// the connection in reconnecting state if it failed to connect right away. |
| 251 |
nc, err := nats.Connect(nats.DefaultURL, |
| 252 |
nats.RetryOnFailedConnect(true), |
| 253 |
nats.MaxReconnects(10), |
| 254 |
nats.ReconnectWait(time.Second), |
| 255 |
nats.ReconnectHandler(func(_ *nats.Conn) { |
| 256 |
// Note that this will be invoked for the first asynchronous connect. |
| 257 |
})) |
| 258 |
if err != nil { |
| 259 |
// Should not return an error even if it can't connect, but you still |
| 260 |
// need to check in case there are some configuration errors. |
| 261 |
} |
| 262 |
|
| 263 |
// Flush connection to server, returns when all messages have been processed. |
| 264 |
nc.Flush() |
| 265 |
fmt.Println("All clear!") |
| 266 |
|
| 267 |
// FlushTimeout specifies a timeout value as well. |
| 268 |
err := nc.FlushTimeout(1*time.Second) |
| 269 |
if err != nil { |
| 270 |
fmt.Println("Flushed timed out!") |
| 271 |
} else { |
| 272 |
fmt.Println("All clear!") |
| 273 |
} |
| 274 |
|
| 275 |
// Auto-unsubscribe after MAX_WANTED messages received |
| 276 |
const MAX_WANTED = 10 |
| 277 |
sub, err := nc.Subscribe("foo") |
| 278 |
sub.AutoUnsubscribe(MAX_WANTED) |
| 279 |
|
| 280 |
// Multiple connections |
| 281 |
nc1 := nats.Connect("nats://host1:4222") |
| 282 |
nc2 := nats.Connect("nats://host2:4222") |
| 283 |
|
| 284 |
nc1.Subscribe("foo", func(m *Msg) { |
| 285 |
fmt.Printf("Received a message: %s\n", string(m.Data)) |
| 286 |
}) |
| 287 |
|
| 288 |
nc2.Publish("foo", []byte("Hello World!")) |
| 289 |
|
| 290 |
``` |
| 291 |
|
| 292 |
## Clustered Usage |
| 293 |
|
| 294 |
```go |
| 295 |
|
| 296 |
var servers = "nats://localhost:1222, nats://localhost:1223, nats://localhost:1224" |
| 297 |
|
| 298 |
nc, err := nats.Connect(servers) |
| 299 |
|
| 300 |
// Optionally set ReconnectWait and MaxReconnect attempts. |
| 301 |
// This example means 10 seconds total per backend. |
| 302 |
nc, err = nats.Connect(servers, nats.MaxReconnects(5), nats.ReconnectWait(2 * time.Second)) |
| 303 |
|
| 304 |
// You can also add some jitter for the reconnection. |
| 305 |
// This call will add up to 500 milliseconds for non TLS connections and 2 seconds for TLS connections. |
| 306 |
// If not specified, the library defaults to 100 milliseconds and 1 second, respectively. |
| 307 |
nc, err = nats.Connect(servers, nats.ReconnectJitter(500*time.Millisecond, 2*time.Second)) |
| 308 |
|
| 309 |
// You can also specify a custom reconnect delay handler. If set, the library will invoke it when it has tried |
| 310 |
// all URLs in its list. The value returned will be used as the total sleep time, so add your own jitter. |
| 311 |
// The library will pass the number of times it went through the whole list. |
| 312 |
nc, err = nats.Connect(servers, nats.CustomReconnectDelay(func(attempts int) time.Duration { |
| 313 |
return someBackoffFunction(attempts) |
| 314 |
})) |
| 315 |
|
| 316 |
// Optionally disable randomization of the server pool |
| 317 |
nc, err = nats.Connect(servers, nats.DontRandomize()) |
| 318 |
|
| 319 |
// Setup callbacks to be notified on disconnects, reconnects and connection closed. |
| 320 |
nc, err = nats.Connect(servers, |
| 321 |
nats.DisconnectErrHandler(func(nc *nats.Conn, err error) { |
| 322 |
fmt.Printf("Got disconnected! Reason: %q\n", err) |
| 323 |
}), |
| 324 |
nats.ReconnectHandler(func(nc *nats.Conn) { |
| 325 |
fmt.Printf("Got reconnected to %v!\n", nc.ConnectedUrl()) |
| 326 |
}), |
| 327 |
nats.ClosedHandler(func(nc *nats.Conn) { |
| 328 |
fmt.Printf("Connection closed. Reason: %q\n", nc.LastError()) |
| 329 |
}) |
| 330 |
) |
| 331 |
|
| 332 |
// When connecting to a mesh of servers with auto-discovery capabilities, |
| 333 |
// you may need to provide a username/password or token in order to connect |
| 334 |
// to any server in that mesh when authentication is required. |
| 335 |
// Instead of providing the credentials in the initial URL, you will use |
| 336 |
// new option setters: |
| 337 |
nc, err = nats.Connect("nats://localhost:4222", nats.UserInfo("foo", "bar")) |
| 338 |
|
| 339 |
// For token based authentication: |
| 340 |
nc, err = nats.Connect("nats://localhost:4222", nats.Token("S3cretT0ken")) |
| 341 |
|
| 342 |
// You can even pass the two at the same time in case one of the servers |
| 343 |
// in the mesh requires token instead of user name and password. |
| 344 |
nc, err = nats.Connect("nats://localhost:4222", |
| 345 |
nats.UserInfo("foo", "bar"), |
| 346 |
nats.Token("S3cretT0ken")) |
| 347 |
|
| 348 |
// Note that if credentials are specified in the initial URLs, they take |
| 349 |
// precedence on the credentials specified through the options. |
| 350 |
// For instance, in the connect call below, the client library will use |
| 351 |
// the user "my" and password "pwd" to connect to localhost:4222, however, |
| 352 |
// it will use username "foo" and password "bar" when (re)connecting to |
| 353 |
// a different server URL that it got as part of the auto-discovery. |
| 354 |
nc, err = nats.Connect("nats://my:pwd@localhost:4222", nats.UserInfo("foo", "bar")) |
| 355 |
|
| 356 |
``` |
| 357 |
|
| 358 |
## Context support (+Go 1.7) |
| 359 |
|
| 360 |
```go |
| 361 |
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 362 |
defer cancel() |
| 363 |
|
| 364 |
nc, err := nats.Connect(nats.DefaultURL) |
| 365 |
|
| 366 |
// Request with context |
| 367 |
msg, err := nc.RequestWithContext(ctx, "foo", []byte("bar")) |
| 368 |
|
| 369 |
// Synchronous subscriber with context |
| 370 |
sub, err := nc.SubscribeSync("foo") |
| 371 |
msg, err := sub.NextMsgWithContext(ctx) |
| 372 |
|
| 373 |
``` |
| 374 |
|
| 375 |
## Backward compatibility |
| 376 |
|
| 377 |
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. |
| 378 |
However, it's important to clarify our stance on certain types of changes: |
| 379 |
|
| 380 |
- **Expanding structures:** |
| 381 |
Adding new fields to structs is not considered a breaking change. |
| 382 |
|
| 383 |
- **Adding methods to exported interfaces:** |
| 384 |
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. |
| 385 |
|
| 386 |
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. |
| 387 |
|
| 388 |
## Testing |
| 389 |
|
| 390 |
See [TESTING.md](TESTING.md) for how to run the test suite locally. |
| 391 |
|
| 392 |
## License |
| 393 |
|
| 394 |
Unless otherwise noted, the NATS source files are distributed |
| 395 |
under the Apache Version 2.0 license found in the LICENSE file. |
| 396 |
|
| 397 |
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats?ref=badge_large) |