Categorygithub.com/nats-io/nats.go
modulepackage
1.39.1
Repository: https://github.com/nats-io/nats.go.git
Documentation: pkg.go.dev

# README

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

# To get the latest released Go client:
go get github.com/nats-io/nats.go@latest

# To get a specific version:
go get github.com/nats-io/[email protected]

# Note that the latest major version for NATS Server is v2:
go get github.com/nats-io/nats-server/v2@latest

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 API Reference

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.

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)
}

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)

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

# Packages

# Functions

AckAll when acking a sequence number, this implicitly acks all sequences below this one as well.
AckExplicit requires ack or nack for all messages.
AckNone requires no acks for delivered messages.
APIPrefix changes the default prefix used for the JetStream API.
BackOff is an array of time durations that represent the time to delay based on delivery count.
Bind binds a subscription to an existing consumer from a stream without attempting to create.
BindStream binds a consumer to a stream explicitly based on a name.
ClientCert is a helper option to provide the client certificate from a file.
ClientTLSConfig is an Option to set the TLS configuration for secure connections.
ClosedHandler is an Option to set the closed handler.
Compression is an Option to indicate if this connection supports compression.
Connect will attempt to connect to the NATS system.
ConnectHandler is an Option to set the connected handler.
ConsumerFilterSubjects can be used to set multiple subject filters on the consumer.
ConsumerMemoryStorage sets the memory storage to true for a consumer.
ConsumerName sets the name for a consumer.
ConsumerReplicas sets the number of replica count for a consumer.
Context returns an option that can be used to configure a context for APIs that are context aware such as those part of the JetStream interface.
CustomInboxPrefix configures the request + reply inbox prefix.
CustomReconnectDelay is an Option to set the CustomReconnectDelayCB option.
DecodeHeadersMsg will decode and headers.
DecodeObjectDigest decodes base64 hash.
DeliverAll will configure a Consumer to receive all the messages from a Stream.
DeliverLast configures a Consumer to receive messages starting with the latest one.
DeliverLastPerSubject configures a Consumer to receive messages starting with the latest one for each filtered subject.
DeliverNew configures a Consumer to receive messages published after the subscription.
DeliverSubject specifies the JetStream consumer deliver subject.
Description will set the description for the created consumer.
Dialer is an Option to set the dialer which will be used when attempting to establish a connection.
DirectGet is an option that can be used to make GetMsg() or GetLastMsg() retrieve message directly from a group of servers (leader and replicas) if the stream was created with the AllowDirect option.
DirectGetNext is an option that can be used to make GetMsg() retrieve message directly from a group of servers (leader and replicas) if the stream was created with the AllowDirect option.
DisconnectErrHandler is an Option to set the disconnected error handler.
DisconnectHandler is an Option to set the disconnected handler.
DiscoveredServersHandler is an Option to set the new servers handler.
Domain changes the domain part of JetStream API prefix.
DontRandomize is an Option to turn off randomizing the server pool.
DrainTimeout is an Option to set the timeout for draining a connection.
Durable defines the consumer name for JetStream durable subscribers.
EnableFlowControl enables flow control for a push based consumer.
EncoderForType will return the registered Encoder for the encType.
ErrorHandler is an Option to set the async error handler.
ExpectLastMsgId sets the expected last msgId in the response from the publish.
ExpectLastSequence sets the expected sequence in the response from the publish.
ExpectLastSequencePerSubject sets the expected sequence per subject in the response from the publish.
ExpectStream sets the expected stream to respond from the publish.
FlusherTimeout is an Option to set the write (and flush) timeout on a connection.
GetDefaultOptions returns default configuration options for the client.
GetObjectDigestValue calculates the base64 value of hashed data.
GetObjectInfoShowDeleted makes GetInfo() return object if it was marked as deleted.
GetObjectShowDeleted makes Get() return object if it was marked as deleted.
HeadersOnly() will instruct the consumer to only deliver headers and no payloads.
IdleHeartbeat enables push based consumers to have idle heartbeats delivered.
IgnoreAuthErrorAbort opts out of the default connect behavior of aborting subsequent reconnect attempts if server returns the same auth error twice.
IgnoreDeletes will have the key watcher not pass any deleted keys.
InactiveThreshold indicates how long the server should keep a consumer after detecting a lack of activity.
IncludeHistory instructs the key watcher to include historical values as well.
InProcessServer is an Option that will try to establish a direction to a NATS server running within the process instead of dialing via TCP.
LameDuckModeHandler sets the callback to invoke when the server notifies the connection that it entered lame duck mode, that is, going to gradually disconnect all its connections before shutting down.
LastRevision deletes if the latest revision matches.
ListObjectsShowDeleted makes ListObjects() return deleted objects.
ManualAck disables auto ack functionality for async subscriptions.
MaxAckPending sets the number of outstanding acks that are allowed before message delivery is halted.
MaxDeliver sets the number of redeliveries for a message.
MaxPingsOutstanding is an Option to set the maximum number of ping requests that can go unanswered by the server before closing the connection.
MaxReconnects is an Option to set the maximum number of reconnect attempts.
MaxRequestBatch sets the maximum pull consumer batch size that a Fetch() can request.
MaxRequestExpires sets the maximum pull consumer request expiration that a Fetch() can request (using the Fetch's timeout value).
MaxRequesMaxBytes sets the maximum pull consumer request bytes that a Fetch() can receive.
MetaOnly instructs the key watcher to retrieve only the entry meta data, not the entry value.
MsgId sets the message ID used for deduplication.
Name is an Option to set the client name.
NewEncodedConn will wrap an existing Connection and utilize the appropriate registered encoder.
NewInbox will return an inbox string which can be used for directed replies from subscribers.
NewMsg creates a message for publishing that will use headers.
Nkey will set the public Nkey and the signature callback to sign the server nonce.
NkeyOptionFromSeed will load an nkey pair from a seed file.
NoCallbacksAfterClientClose is an Option to disable callbacks when user code calls Close().
NoEcho is an Option to turn off messages echoing back from a server.
NoReconnect is an Option to turn off reconnect behavior.
OrderedConsumer will create a FIFO direct/ephemeral consumer for in order delivery of messages.
PingInterval is an Option to set the period for client ping commands.
ProxyPath is an option for websocket connections that adds a path to connections url.
PublishAsyncErrHandler sets the error handler for async publishes in JetStream.
PublishAsyncMaxPending sets the maximum outstanding async publishes that can be inflight at one time.
PullMaxWaiting defines the max inflight pull requests.
RateLimit is the Bits per sec rate limit applied to a push consumer.
ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.
ReconnectHandler is an Option to set the reconnected handler.
ReconnectJitter is an Option to set the upper bound of a random delay added ReconnectWait.
ReconnectWait is an Option to set the wait time between reconnect attempts.
RegisterEncoder will register the encType with the given Encoder.
ReplayInstant replays the messages as fast as possible.
ReplayOriginal replays the messages at the original speed.
RetryAttempts sets the retry number of attempts when ErrNoResponders is encountered.
RetryOnFailedConnect sets the connection in reconnecting state right away if it can't connect to a server in the initial set.
RetryWait sets the retry wait time when ErrNoResponders is encountered.
RootCAs is a helper option to provide the RootCAs pool from a list of filenames.
Secure is an Option to enable TLS secure connections that skip server verification by default.
SetCustomDialer is an Option to set a custom dialer which will be used when attempting to establish a connection.
SkipConsumerLookup will omit looking up consumer when [Bind], [Durable] or [ConsumerName] are provided.
SkipHostLookup is an Option to skip the host lookup when connecting to a server.
StallWait sets the max wait when the producer becomes stall producing messages.
StartSequence configures a Consumer to receive messages from a start sequence.
StartTime configures a Consumer to receive messages from a start time.
StreamListFilter is an option that can be used to configure `StreamsInfo()` and `StreamNames()` requests.
SyncQueueLen will set the maximum queue len for the internal channel used for SubscribeSync().
Timeout is an Option to set the timeout for Dial on a connection.
TLSHandshakeFirst is an Option to perform the TLS handshake first, that is before receiving the INFO protocol.
Token is an Option to set the token to use when a token is not included directly in the URLs and when a token handler is not provided.
TokenHandler is an Option to set the token handler to use when a token is not included directly in the URLs and when a token is not set.
UpdatesOnly instructs the key watcher to only include updates on values (without latest values when started).
UseLegacyDurableConsumers makes JetStream use the legacy (pre nats-server v2.9.0) subjects for consumer creation.
UseOldRequestStyle is an Option to force usage of the old Request style.
UserCredentials is a convenience function that takes a filename for a user's JWT and a filename for the user's private Nkey seed.
UserInfo is an Option to set the username and password to use when not included directly in the URLs.
UserJWT will set the callbacks to retrieve the user's JWT and the signature callback to sign the server nonce.
UserJWTAndSeed is a convenience function that takes the JWT and seed values as strings.

# Constants

ACCOUNT_AUTHENTICATION_EXPIRED_ERR is for when nats server account authorization has expired.
AckAllPolicy when acking a sequence number, this implicitly acks all sequences below this one as well.
AckExplicitPolicy requires ack or nack for all messages.
AckNonePolicy requires no acks for delivered messages.
Used to watch all keys.
The different types of subscription types.
AUTHENTICATION_EXPIRED_ERR is for when nats server user authorization has expired.
AUTHENTICATION_REVOKED_ERR is for when user authorization has been revoked.
AUTHORIZATION_ERR is for when nats server user authorization has failed.
The different types of subscription types.
Indexed names into the Registered Encoders.
Default Constants.
Default Constants.
64k.
Default Constants.
Default Constants.
Default Constants.
Default Constants.
Default number of retries.
Default time wait between retries on Publish iff err is NoResponders.
8MB.
Default Constants.
Default Constants.
Default Constants.
DefaultSubPendingBytesLimit is 64MB.
DefaultSubPendingMsgsLimit will be 512k msgs.
Default Constants.
Default Constants.
DeliverAllPolicy starts delivering messages from the very beginning of a stream.
DeliverByStartSequencePolicy will deliver messages starting from a given sequence.
DeliverByStartTimePolicy will deliver messages starting from a given time.
DeliverLastPerSubjectPolicy will start the consumer with the last message for all subjects received.
DeliverLastPolicy will start the consumer with the last sequence received.
DeliverNewPolicy will only deliver new messages that are sent after the consumer is created.
DiscardNew will fail to store new messages.
DiscardOld will remove older messages to return to the limits.
Headers for published messages.
Headers for published messages.
Headers for published messages.
Headers for published messages.
FileStorage specifies on disk storage.
Indexed names into the Registered Encoders.
InboxPrefix is the prefix for all inbox subjects.
InterestPolicy specifies that when all known observables have acknowledged a message it can be removed.
Headers for republished messages and direct gets.
Indexed names into the Registered Encoders.
Headers for republished messages and direct gets.
Headers for republished messages and direct gets.
Headers for republished messages and direct gets.
Headers for republished messages and direct gets.
Used to watch all keys.
Default Constants.
LimitsPolicy (default) means that messages are retained until any given limit is reached.
MAX_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit.
MAX_SUBSCRIPTIONS_ERR is for when nats server denies the connection due to server subscriptions limit.
MemoryStorage specifies in memory only.
Headers for published messages.
Headers for published messages.
Rollups, can be subject only or all messages.
Rollups, can be subject only or all messages.
MsgSize is a header that will be part of a consumer's delivered message if HeadersOnly requested.
The different types of subscription types.
PERMISSIONS_ERR is for when nats server subject authorization has failed.
The different types of subscription types.
ReplayInstantPolicy will replay messages as fast as possible.
ReplayOriginalPolicy will maintain the same timing as the messages were received.
Default Constants.
STALE_CONNECTION is for detection and proper handling of stale connections.
The different types of subscription types.
Default Constants.
WorkQueuePolicy specifies that when the first worker or subscriber acknowledges the message it can be removed.

# Variables

Deprecated: Use GetDefaultOptions() instead.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
ErrBadRequest is returned when invalid request is sent to JetStream API.
Errors.
Errors.
Errors.
Errors.
ErrCantAckIfConsumerAckNone is returned when attempting to ack a message for consumer with AckNone policy set.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
ErrConsumerConfigRequired is returned when empty consumer consuguration is supplied to add/update consumer.
ErrConsumerDeleted is returned when attempting to send pull request to a consumer which does not exist.
ErrConsumerLeadershipChanged is returned when pending requests are no longer valid after leadership has changed.
ErrConsumerMultipleFilterSubjectsNotSupported is returned when the connected nats-server version does not support setting multiple filter subjects with filter_subjects field.
ErrConsumerNameAlreadyInUse is an error returned when consumer with given name already exists.
ErrConsumerNameRequired is returned when the provided consumer durable name is empty.
ErrConsumerNotActive is an error returned when consumer is not active.
ErrConsumerNotFound is an error returned when consumer with given name does not exist.
ErrContextAndTimeout is returned when attempting to use both context and timeout.
Errors.
Errors.
ErrDuplicateFilterSubjects is returned when both FilterSubject and FilterSubjects are specified when creating consumer.
ErrEmptyFilter is returned when a filter in FilterSubjects is empty.
Errors.
Errors.
Errors.
Errors.
Errors.
ErrInvalidConsumerName is returned when the provided consumer name is invalid (contains '.' or ' ').
Errors.
Deprecated: ErrInvalidDurableName is no longer returned and will be removed in future releases.
ErrInvalidFilterSubject is returned when the provided filter subject is invalid.
ErrInvalidJSAck is returned when JetStream ack from message publish is invalid.
Errors.
Errors.
ErrInvalidStreamName is returned when the provided stream name is invalid (contains '.' or ' ').
ErrJetStreamNotEnabled is an error returned when JetStream is not enabled for an account.
ErrJetStreamNotEnabledForAccount is an error returned when JetStream is not enabled for an account.
ErrJetStreamPublisherClosed is returned for each unfinished ack future when JetStream.Cleanup is called.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
ErrMsgAlreadyAckd is returned when attempting to acknowledge message more than once.
Errors.
Errors.
ErrMsgNotFound is returned when message with provided sequence number does npt exist.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.
ErrNoHeartbeat is returned when no heartbeat is received from server when sending requests with pull consumer.
Errors.
Errors.
ErrNoMatchingStream is returned when stream lookup by subject is unsuccessful.
Errors.
Errors.
ErrNoStreamResponse is returned when there is no response from stream (e.g.
ErrNotJSMessage is returned when attempting to get metadata from non JetStream message .
Errors.
ErrDuplicateFilterSubjects is returned when filter subjects overlap when creating consumer.
Errors.
ErrPullSubscribeRequired is returned when attempting to use subscribe methods not suitable for pull consumers for pull consumers.
ErrPullSubscribeToPushConsumer is returned when attempting to use PullSubscribe on push consumer.
Errors.
Errors.
Errors.
Errors.
Errors.
ErrStreamConfigRequired is returned when empty stream configuration is supplied to add/update stream.
ErrStreamNameAlreadyInUse is returned when a stream with given name already exists and has a different configuration.
ErrStreamNameRequired is returned when the provided stream name is empty.
ErrStreamNotFound is an error returned when stream with given name does not exist.
ErrStreamSourceMultipleSubjectTransformsNotSupported is returned when the connected nats-server version does not support setting the stream sources.
ErrStreamSourceNotSupported is returned when the connected nats-server version does not support setting the stream sources.
ErrStreamSourceSubjectTransformNotSupported is returned when the connected nats-server version does not support setting the stream source subject transform.
ErrStreamSubjectTransformNotSupported is returned when the connected nats-server version does not support setting the stream subject transform.
ErrSubjectMismatch is returned when the provided subject does not match consumer's filter subject.
ErrSubscriptionClosed is returned when attempting to send pull request to a closed subscription.
Errors.
Errors.
Errors.
Errors.
Errors.
Errors.

# Structs

AccountInfo contains info about the JetStream usage from the current account.
AccountLimits includes the JetStream limits of the current account.
APIError is included in all API responses if there was an error.
APIStats reports on API calls to JetStream for this account.
ClientTrace can be used to trace API interactions for the JetStream Context.
ClusterInfo shows information about the underlying set of servers that make up the stream or consumer.
A Conn represents a bare connection to a nats-server.
ConsumerConfig is the configuration of a JetStream consumer.
ConsumerInfo is the info from a JetStream consumer.
ContextOpt is an option used to set a context.Context.
EncodedConn are the preferred way to interface with NATS.
ErrConsumerSequenceMismatch represents an error from a consumer that received a Heartbeat including sequence different to the one expected from the view of the client.
ExternalStream allows you to qualify access to a stream source in another account.
KeyValueBucketStatus represents status of a Bucket, implements KeyValueStatus.
KeyValueConfig is for configuring a KeyValue store.
Msg represents a message delivered by NATS.
MsgMetadata is the JetStream metadata associated with received messages.
ObjectBucketStatus represents status of a Bucket, implements ObjectStoreStatus.
ObjectInfo is meta plus instance information.
ObjectLink is used to embed links to other buckets and objects.
ObjectMeta is high level information about an object.
ObjectMetaOptions.
ObjectStoreConfig is the config for the object store.
Options can be used to create a customized connection.
PeerInfo shows information about all the peers in the cluster that are supporting the stream or consumer.
Placement is used to guide placement of streams in clustered JetStream.
PubAck is an ack received after successfully publishing a message.
RawStreamMsg is a raw message stored in JetStream.
RePublish is for republishing messages once committed to a stream.
SequenceInfo has both the consumer and the stream sequence and last activity.
SequencePair includes the consumer and stream sequence info from a JetStream consumer.
Tracks various stats received and sent on this connection, including counts for messages and bytes.
StreamAlternate is an alternate stream represented by a mirror.
StreamConfig will determine the properties for a stream.
StreamConsumerLimits are the limits for a consumer on a stream.
StreamInfo shows config and current state for this stream.
StreamPurgeRequest is optional request information to the purge API.
StreamSource dictates how streams can source from other streams.
StreamSourceInfo shows information about an upstream stream source.
StreamState is information about the given stream.
SubjectTransformConfig is for applying a subject transform (to matching messages) before doing anything else when a new message is received.
Subscription represents interest in a given subject.

# Interfaces

AckOpt are the options that can be passed when acknowledge a message.
CustomDialer can be used to specify any dialer, not necessarily a *net.Dialer.
Encoder interface is for all register encoders Deprecated: Encoded connections are no longer supported.
JetStream allows persistent messaging through JetStream.
JetStreamContext allows JetStream messaging and stream management.
JetStreamError is an error result that happens when using JetStream.
JetStreamManager manages JetStream Streams and Consumers.
JSOpt configures a JetStreamContext.
KeyLister is used to retrieve a list of key value store keys.
KeyValue contains methods to operate on a KeyValue store.
KeyValueEntry is a retrieved entry for Get or List or Watch.
KeyValueManager is used to manage KeyValue stores.
KeyValueStatus is run-time status about a Key-Value bucket.
KeyWatcher is what is returned when doing a watch.
MessageBatch provides methods to retrieve messages consumed using [Subscribe.FetchBatch].
ObjectResult will return the underlying stream info and also be an io.ReadCloser.
ObjectStore is a blob store capable of storing large objects efficiently in JetStream streams.
ObjectStoreManager creates, loads and deletes Object Stores.
ObjectWatcher is what is returned when doing a watch.
PubAckFuture is a future for a PubAck.
PubOpt configures options for publishing JetStream messages.
PullOpt are the options that can be passed when pulling a batch of messages.
SubOpt configures options for subscribing to JetStream consumers.

# Type aliases

AckPolicy determines how the consumer should acknowledge delivered messages.
AckWait sets the maximum amount of time we will wait for an ack.
AuthTokenHandler is used to generate a new token.
ConnErrHandler is used to process asynchronous events like disconnected connection with the error (if any).
ConnHandler is used for asynchronous events such as disconnected and closed connections.
DeleteMarkersOlderThan indicates that delete or purge markers older than that will be deleted as part of PurgeDeletes() operation, otherwise, only the data will be removed but markers that are recent will be kept.
DeliverPolicy determines how the consumer should select the first message to deliver.
DiscardPolicy determines how to proceed when limits of messages or bytes are reached.
ErrHandler is used to process asynchronous errors encountered while processing inbound messages.
Error code represents JetStream error codes returned by the API.
Handler is a specific callback used for Subscribe.
Header represents the optional Header for a NATS message, based on the implementation of http.Header.
MaxWait sets the maximum amount of time we will wait for a response.
MsgErrHandler is used to process asynchronous errors from JetStream PublishAsync.
MsgHandler is a callback function that processes messages delivered to asynchronous subscribers.
Option is a function on the options for a connection.
PullMaxBytes defines the max bytes allowed for a fetch request.
ReconnectDelayHandler is used to get from the user the desired delay the library should pause before attempting to reconnect again.
ReplayPolicy determines how the consumer should replay messages it already has queued in the stream.
RetentionPolicy determines how messages in a set are retained.
RootCAsHandler is used to fetch and return a set of root certificate authorities that clients use when verifying server certificates.
SignatureHandler is used to sign a nonce from the server while authenticating with nkeys.
Status represents the state of the connection.
StorageType determines how messages are stored for retention.
SubscriptionType is the type of the Subscription.
Status represents the state of the connection.
TLSCertHandler is used to fetch and return tls certificate.
UserInfoCB is used to pass the username and password when establishing connection.
UserJWTHandler is used to fetch and return the account signed JWT for this user.