README

NATS - Go Client

A Go client for the NATS messaging system.

License Apache 2 FOSSA Status Go Report Card Build Status GoDoc Coverage Status

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.10.0

# 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 nats "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()

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


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

License

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

FOSSA Status

Expand ▾ Collapse ▴

Documentation

Overview

    A Go client for the NATS messaging system (https://nats.io).

    A Go client for the NATS messaging system (https://nats.io).

    Index

    Examples

    Constants

    View Source
    const (
    	JSON_ENCODER    = "json"
    	GOB_ENCODER     = "gob"
    	DEFAULT_ENCODER = "default"
    )

      Indexed names into the Registered Encoders.

      View Source
      const (
      	Version                   = "1.10.0"
      	DefaultURL                = "nats://127.0.0.1:4222"
      	DefaultPort               = 4222
      	DefaultMaxReconnect       = 60
      	DefaultReconnectWait      = 2 * time.Second
      	DefaultReconnectJitter    = 100 * time.Millisecond
      	DefaultReconnectJitterTLS = time.Second
      	DefaultTimeout            = 2 * time.Second
      	DefaultPingInterval       = 2 * time.Minute
      	DefaultMaxPingOut         = 2
      	DefaultMaxChanLen         = 8192            // 8k
      	DefaultReconnectBufSize   = 8 * 1024 * 1024 // 8MB
      	RequestChanLen            = 8
      	DefaultDrainTimeout       = 30 * time.Second
      	LangString                = "go"
      )

        Default Constants

        View Source
        const (
        	// STALE_CONNECTION is for detection and proper handling of stale connections.
        	STALE_CONNECTION = "stale connection"
        
        	// PERMISSIONS_ERR is for when nats server subject authorization has failed.
        	PERMISSIONS_ERR = "permissions violation"
        
        	// AUTHORIZATION_ERR is for when nats server user authorization has failed.
        	AUTHORIZATION_ERR = "authorization violation"
        
        	// AUTHENTICATION_EXPIRED_ERR is for when nats server user authorization has expired.
        	AUTHENTICATION_EXPIRED_ERR = "user authentication expired"
        )
        View Source
        const (
        	DISCONNECTED = Status(iota)
        	CONNECTED
        	CLOSED
        	RECONNECTING
        	CONNECTING
        	DRAINING_SUBS
        	DRAINING_PUBS
        )
        View Source
        const (
        	AsyncSubscription = SubscriptionType(iota)
        	SyncSubscription
        	ChanSubscription
        	NilSubscription
        )

          The different types of subscription types.

          View Source
          const (
          	DefaultSubPendingMsgsLimit  = 65536
          	DefaultSubPendingBytesLimit = 65536 * 1024
          )

            Pending Limits

            View Source
            const (
            	OP_START = iota
            	OP_PLUS
            	OP_PLUS_O
            	OP_PLUS_OK
            	OP_MINUS
            	OP_MINUS_E
            	OP_MINUS_ER
            	OP_MINUS_ERR
            	OP_MINUS_ERR_SPC
            	MINUS_ERR_ARG
            	OP_M
            	OP_MS
            	OP_MSG
            	OP_MSG_SPC
            	MSG_ARG
            	MSG_PAYLOAD
            	MSG_END
            	OP_P
            	OP_PI
            	OP_PIN
            	OP_PING
            	OP_PO
            	OP_PON
            	OP_PONG
            	OP_I
            	OP_IN
            	OP_INF
            	OP_INFO
            	OP_INFO_SPC
            	INFO_ARG
            )
            View Source
            const (
            	InboxPrefix = "_INBOX."
            )

              InboxPrefix is the prefix for all inbox subjects.

              View Source
              const MAX_CONTROL_LINE_SIZE = 4096

              Variables

              View Source
              var (
              	ErrConnectionClosed       = errors.New("nats: connection closed")
              	ErrConnectionDraining     = errors.New("nats: connection draining")
              	ErrDrainTimeout           = errors.New("nats: draining connection timed out")
              	ErrConnectionReconnecting = errors.New("nats: connection reconnecting")
              	ErrSecureConnRequired     = errors.New("nats: secure connection required")
              	ErrSecureConnWanted       = errors.New("nats: secure connection not available")
              	ErrBadSubscription        = errors.New("nats: invalid subscription")
              	ErrTypeSubscription       = errors.New("nats: invalid subscription type")
              	ErrBadSubject             = errors.New("nats: invalid subject")
              	ErrBadQueueName           = errors.New("nats: invalid queue name")
              	ErrSlowConsumer           = errors.New("nats: slow consumer, messages dropped")
              	ErrTimeout                = errors.New("nats: timeout")
              	ErrBadTimeout             = errors.New("nats: timeout invalid")
              	ErrAuthorization          = errors.New("nats: authorization violation")
              	ErrAuthExpired            = errors.New("nats: authentication expired")
              	ErrNoServers              = errors.New("nats: no servers available for connection")
              	ErrJsonParse              = errors.New("nats: connect message, json parse error")
              	ErrChanArg                = errors.New("nats: argument needs to be a channel type")
              	ErrMaxPayload             = errors.New("nats: maximum payload exceeded")
              	ErrMaxMessages            = errors.New("nats: maximum messages delivered")
              	ErrSyncSubRequired        = errors.New("nats: illegal call on an async subscription")
              	ErrMultipleTLSConfigs     = errors.New("nats: multiple tls.Configs not allowed")
              	ErrNoInfoReceived         = errors.New("nats: protocol exception, INFO not received")
              	ErrReconnectBufExceeded   = errors.New("nats: outbound buffer limit exceeded")
              	ErrInvalidConnection      = errors.New("nats: invalid connection")
              	ErrInvalidMsg             = errors.New("nats: invalid message or message nil")
              	ErrInvalidArg             = errors.New("nats: invalid argument")
              	ErrInvalidContext         = errors.New("nats: invalid context")
              	ErrNoDeadlineContext      = errors.New("nats: context requires a deadline")
              	ErrNoEchoNotSupported     = errors.New("nats: no echo option not supported by this server")
              	ErrClientIDNotSupported   = errors.New("nats: client ID not supported by this server")
              	ErrUserButNoSigCB         = errors.New("nats: user callback defined without a signature handler")
              	ErrNkeyButNoSigCB         = errors.New("nats: nkey defined without a signature handler")
              	ErrNoUserCB               = errors.New("nats: user callback not defined")
              	ErrNkeyAndUser            = errors.New("nats: user callback and nkey defined")
              	ErrNkeysNotSupported      = errors.New("nats: nkeys not supported by the server")
              	ErrStaleConnection        = errors.New("nats: " + STALE_CONNECTION)
              	ErrTokenAlreadySet        = errors.New("nats: token and token handler both set")
              	ErrMsgNotBound            = errors.New("nats: message is not bound to subscription/connection")
              	ErrMsgNoReply             = errors.New("nats: message does not have a reply")
              	ErrClientIPNotSupported   = errors.New("nats: client IP not supported by this server")
              	ErrDisconnected           = errors.New("nats: server is disconnected")
              )

                Errors

                View Source
                var DefaultOptions = GetDefaultOptions()

                  DEPRECATED: Use GetDefaultOptions() instead. DefaultOptions is not safe for use by multiple clients. For details see #308.

                  Functions

                  func NewInbox

                  func NewInbox() string

                    NewInbox will return an inbox string which can be used for directed replies from subscribers. These are guaranteed to be unique, but can be shared and subscribed to by others.

                    func RegisterEncoder

                    func RegisterEncoder(encType string, enc Encoder)

                      RegisterEncoder will register the encType with the given Encoder. Useful for customization.

                      Types

                      type AuthTokenHandler

                      type AuthTokenHandler func() string

                        AuthTokenHandler is used to generate a new token.

                        type Conn

                        type Conn struct {
                        	// Keep all members for which we use atomic at the beginning of the
                        	// struct and make sure they are all 64bits (or use padding if necessary).
                        	// atomic.* functions crash on 32bit machines if operand is not aligned
                        	// at 64bit. See https://github.com/golang/go/issues/599
                        	Statistics
                        
                        	// Opts holds the configuration of the Conn.
                        	// Modifying the configuration of a running Conn is a race.
                        	Opts Options
                        	// contains filtered or unexported fields
                        }

                          A Conn represents a bare connection to a nats-server. It can send and receive []byte payloads. The connection is safe to use in multiple Go routines concurrently.

                          func Connect

                          func Connect(url string, options ...Option) (*Conn, error)

                            Connect will attempt to connect to the NATS system. The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222 Comma separated arrays are also supported, e.g. urlA, urlB. Options start with the defaults but can be overridden.

                            Example

                              Shows different ways to create a Conn

                              Output:
                              
                              

                              func (*Conn) AuthRequired

                              func (nc *Conn) AuthRequired() bool

                                AuthRequired will return if the connected server requires authorization.

                                func (*Conn) Barrier

                                func (nc *Conn) Barrier(f func()) error

                                  Barrier schedules the given function `f` to all registered asynchronous subscriptions. Only the last subscription to see this barrier will invoke the function. If no subscription is registered at the time of this call, `f()` is invoked right away. ErrConnectionClosed is returned if the connection is closed prior to the call.

                                  func (*Conn) Buffered

                                  func (nc *Conn) Buffered() (int, error)

                                    Buffered will return the number of bytes buffered to be sent to the server. FIXME(dlc) take into account disconnected state.

                                    func (*Conn) ChanQueueSubscribe

                                    func (nc *Conn) ChanQueueSubscribe(subj, group string, ch chan *Msg) (*Subscription, error)

                                      ChanQueueSubscribe will express interest in the given subject. All subscribers with the same queue name will form the queue group and only one member of the group will be selected to receive any given message, which will be placed on the channel. You should not close the channel until sub.Unsubscribe() has been called. Note: This is the same than QueueSubscribeSyncWithChan.

                                      func (*Conn) ChanSubscribe

                                      func (nc *Conn) ChanSubscribe(subj string, ch chan *Msg) (*Subscription, error)

                                        ChanSubscribe will express interest in the given subject and place all messages received on the channel. You should not close the channel until sub.Unsubscribe() has been called.

                                        func (*Conn) Close

                                        func (nc *Conn) Close()

                                          Close will close the connection to the server. This call will release all blocking calls, such as Flush() and NextMsg()

                                          Example
                                          Output:
                                          
                                          

                                          func (*Conn) ConnectedAddr

                                          func (nc *Conn) ConnectedAddr() string

                                            ConnectedAddr returns the connected server's IP

                                            func (*Conn) ConnectedServerId

                                            func (nc *Conn) ConnectedServerId() string

                                              Report the connected server's Id

                                              func (*Conn) ConnectedUrl

                                              func (nc *Conn) ConnectedUrl() string

                                                Report the connected server's Url

                                                func (*Conn) DiscoveredServers

                                                func (nc *Conn) DiscoveredServers() []string

                                                  DiscoveredServers returns only the server urls that have been discovered after a connection has been established. If authentication is enabled, use UserInfo or Token when connecting with these urls.

                                                  func (*Conn) Drain

                                                  func (nc *Conn) Drain() error

                                                    Drain will put a connection into a drain state. All subscriptions will immediately be put into a drain state. Upon completion, the publishers will be drained and can not publish any additional messages. Upon draining of the publishers, the connection will be closed. Use the ClosedCB() option to know when the connection has moved from draining to closed.

                                                    func (*Conn) Flush

                                                    func (nc *Conn) Flush() error

                                                      Flush will perform a round trip to the server and return when it receives the internal reply.

                                                      Example
                                                      Output:
                                                      
                                                      

                                                      func (*Conn) FlushTimeout

                                                      func (nc *Conn) FlushTimeout(timeout time.Duration) (err error)

                                                        FlushTimeout allows a Flush operation to have an associated timeout.

                                                        Example
                                                        Output:
                                                        
                                                        

                                                        func (*Conn) FlushWithContext

                                                        func (nc *Conn) FlushWithContext(ctx context.Context) error

                                                          FlushWithContext will allow a context to control the duration of a Flush() call. This context should be non-nil and should have a deadline set. We will return an error if none is present.

                                                          func (*Conn) GetClientID

                                                          func (nc *Conn) GetClientID() (uint64, error)

                                                            GetClientID returns the client ID assigned by the server to which the client is currently connected to. Note that the value may change if the client reconnects. This function returns ErrClientIDNotSupported if the server is of a version prior to 1.2.0.

                                                            func (*Conn) GetClientIP

                                                            func (nc *Conn) GetClientIP() (net.IP, error)

                                                              GetClientIP returns the client IP as known by the server. Supported as of server version 2.1.6.

                                                              func (*Conn) IsClosed

                                                              func (nc *Conn) IsClosed() bool

                                                                IsClosed tests if a Conn has been closed.

                                                                func (*Conn) IsConnected

                                                                func (nc *Conn) IsConnected() bool

                                                                  IsConnected tests if a Conn is connected.

                                                                  func (*Conn) IsDraining

                                                                  func (nc *Conn) IsDraining() bool

                                                                    IsDraining tests if a Conn is in the draining state.

                                                                    func (*Conn) IsReconnecting

                                                                    func (nc *Conn) IsReconnecting() bool

                                                                      IsReconnecting tests if a Conn is reconnecting.

                                                                      func (*Conn) LastError

                                                                      func (nc *Conn) LastError() error

                                                                        LastError reports the last error encountered via the connection. It can be used reliably within ClosedCB in order to find out reason why connection was closed for example.

                                                                        func (*Conn) MaxPayload

                                                                        func (nc *Conn) MaxPayload() int64

                                                                          MaxPayload returns the size limit that a message payload can have. This is set by the server configuration and delivered to the client upon connect.

                                                                          func (*Conn) NewRespInbox

                                                                          func (nc *Conn) NewRespInbox() string

                                                                            NewRespInbox is the new format used for _INBOX.

                                                                            func (*Conn) NumSubscriptions

                                                                            func (nc *Conn) NumSubscriptions() int

                                                                              NumSubscriptions returns active number of subscriptions.

                                                                              func (*Conn) Publish

                                                                              func (nc *Conn) Publish(subj string, data []byte) error

                                                                                Publish publishes the data argument to the given subject. The data argument is left untouched and needs to be correctly interpreted on the receiver.

                                                                                Example
                                                                                Output:
                                                                                
                                                                                

                                                                                func (*Conn) PublishMsg

                                                                                func (nc *Conn) PublishMsg(m *Msg) error

                                                                                  PublishMsg publishes the Msg structure, which includes the Subject, an optional Reply and an optional Data field.

                                                                                  Example
                                                                                  Output:
                                                                                  
                                                                                  

                                                                                  func (*Conn) PublishRequest

                                                                                  func (nc *Conn) PublishRequest(subj, reply string, data []byte) error

                                                                                    PublishRequest will perform a Publish() excpecting a response on the reply subject. Use Request() for automatically waiting for a response inline.

                                                                                    func (*Conn) QueueSubscribe

                                                                                    func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error)

                                                                                      QueueSubscribe creates an asynchronous queue subscriber on the given subject. All subscribers with the same queue name will form the queue group and only one member of the group will be selected to receive any given message asynchronously.

                                                                                      Example
                                                                                      Output:
                                                                                      
                                                                                      

                                                                                      func (*Conn) QueueSubscribeSync

                                                                                      func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error)

                                                                                        QueueSubscribeSync creates a synchronous queue subscriber on the given subject. All subscribers with the same queue name will form the queue group and only one member of the group will be selected to receive any given message synchronously using Subscription.NextMsg().

                                                                                        func (*Conn) QueueSubscribeSyncWithChan

                                                                                        func (nc *Conn) QueueSubscribeSyncWithChan(subj, queue string, ch chan *Msg) (*Subscription, error)

                                                                                          QueueSubscribeSyncWithChan will express interest in the given subject. All subscribers with the same queue name will form the queue group and only one member of the group will be selected to receive any given message, which will be placed on the channel. You should not close the channel until sub.Unsubscribe() has been called. Note: This is the same than ChanQueueSubscribe.

                                                                                          func (*Conn) RTT

                                                                                          func (nc *Conn) RTT() (time.Duration, error)

                                                                                            RTT calculates the round trip time between this client and the server.

                                                                                            func (*Conn) Request

                                                                                            func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error)

                                                                                              Request will send a request payload and deliver the response message, or an error, including a timeout if no message was received properly.

                                                                                              Example
                                                                                              Output:
                                                                                              
                                                                                              

                                                                                              func (*Conn) RequestWithContext

                                                                                              func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error)

                                                                                                RequestWithContext takes a context, a subject and payload in bytes and request expecting a single response.

                                                                                                func (*Conn) Servers

                                                                                                func (nc *Conn) Servers() []string

                                                                                                  Servers returns the list of known server urls, including additional servers discovered after a connection has been established. If authentication is enabled, use UserInfo or Token when connecting with these urls.

                                                                                                  func (*Conn) SetClosedHandler

                                                                                                  func (nc *Conn) SetClosedHandler(cb ConnHandler)

                                                                                                    SetClosedHandler will set the reconnect event handler.

                                                                                                    func (*Conn) SetDisconnectErrHandler

                                                                                                    func (nc *Conn) SetDisconnectErrHandler(dcb ConnErrHandler)

                                                                                                      SetDisconnectErrHandler will set the disconnect event handler.

                                                                                                      func (*Conn) SetDisconnectHandler

                                                                                                      func (nc *Conn) SetDisconnectHandler(dcb ConnHandler)

                                                                                                        SetDisconnectHandler will set the disconnect event handler. DEPRECATED: Use SetDisconnectErrHandler

                                                                                                        func (*Conn) SetDiscoveredServersHandler

                                                                                                        func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler)

                                                                                                          SetDiscoveredServersHandler will set the discovered servers handler.

                                                                                                          func (*Conn) SetErrorHandler

                                                                                                          func (nc *Conn) SetErrorHandler(cb ErrHandler)

                                                                                                            SetErrorHandler will set the async error handler.

                                                                                                            func (*Conn) SetReconnectHandler

                                                                                                            func (nc *Conn) SetReconnectHandler(rcb ConnHandler)

                                                                                                              SetReconnectHandler will set the reconnect event handler.

                                                                                                              func (*Conn) Stats

                                                                                                              func (nc *Conn) Stats() Statistics

                                                                                                                Stats will return a race safe copy of the Statistics section for the connection.

                                                                                                                func (*Conn) Status

                                                                                                                func (nc *Conn) Status() Status

                                                                                                                  Status returns the current state of the connection.

                                                                                                                  func (*Conn) Subscribe

                                                                                                                  func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error)

                                                                                                                    Subscribe will express interest in the given subject. The subject can have wildcards (partial:*, full:>). Messages will be delivered to the associated MsgHandler.

                                                                                                                    Example

                                                                                                                      This Example shows an asynchronous subscriber.

                                                                                                                      Output:
                                                                                                                      
                                                                                                                      

                                                                                                                      func (*Conn) SubscribeSync

                                                                                                                      func (nc *Conn) SubscribeSync(subj string) (*Subscription, error)

                                                                                                                        SubscribeSync will express interest on the given subject. Messages will be received synchronously using Subscription.NextMsg().

                                                                                                                        Example

                                                                                                                          This Example shows a synchronous subscriber.

                                                                                                                          Output:
                                                                                                                          
                                                                                                                          

                                                                                                                          func (*Conn) TLSRequired

                                                                                                                          func (nc *Conn) TLSRequired() bool

                                                                                                                            TLSRequired will return if the connected server requires TLS connections.

                                                                                                                            type ConnErrHandler

                                                                                                                            type ConnErrHandler func(*Conn, error)

                                                                                                                              ConnErrHandler is used to process asynchronous events like disconnected connection with the error (if any).

                                                                                                                              type ConnHandler

                                                                                                                              type ConnHandler func(*Conn)

                                                                                                                                ConnHandler is used for asynchronous events such as disconnected and closed connections.

                                                                                                                                type CustomDialer

                                                                                                                                type CustomDialer interface {
                                                                                                                                	Dial(network, address string) (net.Conn, error)
                                                                                                                                }

                                                                                                                                  CustomDialer can be used to specify any dialer, not necessarily a *net.Dialer.

                                                                                                                                  type EncodedConn

                                                                                                                                  type EncodedConn struct {
                                                                                                                                  	Conn *Conn
                                                                                                                                  	Enc  Encoder
                                                                                                                                  }

                                                                                                                                    EncodedConn are the preferred way to interface with NATS. They wrap a bare connection to a nats server and have an extendable encoder system that will encode and decode messages from raw Go types.

                                                                                                                                    func NewEncodedConn

                                                                                                                                    func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error)

                                                                                                                                      NewEncodedConn will wrap an existing Connection and utilize the appropriate registered encoder.

                                                                                                                                      Example

                                                                                                                                        Shows how to wrap a Conn into an EncodedConn

                                                                                                                                        Output:
                                                                                                                                        
                                                                                                                                        

                                                                                                                                        func (*EncodedConn) BindRecvChan

                                                                                                                                        func (c *EncodedConn) BindRecvChan(subject string, channel interface{}) (*Subscription, error)

                                                                                                                                          BindRecvChan binds a channel for receive operations from NATS.

                                                                                                                                          Example

                                                                                                                                            BindRecvChan() allows binding of a Go channel to a nats subject for subscribe operations. The Encoder attached to the EncodedConn will be used for un-marshaling.

                                                                                                                                            Output:
                                                                                                                                            
                                                                                                                                            

                                                                                                                                            func (*EncodedConn) BindRecvQueueChan

                                                                                                                                            func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel interface{}) (*Subscription, error)

                                                                                                                                              BindRecvQueueChan binds a channel for queue-based receive operations from NATS.

                                                                                                                                              func (*EncodedConn) BindSendChan

                                                                                                                                              func (c *EncodedConn) BindSendChan(subject string, channel interface{}) error

                                                                                                                                                BindSendChan binds a channel for send operations to NATS.

                                                                                                                                                Example

                                                                                                                                                  BindSendChan() allows binding of a Go channel to a nats subject for publish operations. The Encoder attached to the EncodedConn will be used for marshaling.

                                                                                                                                                  Output:
                                                                                                                                                  
                                                                                                                                                  

                                                                                                                                                  func (*EncodedConn) Close

                                                                                                                                                  func (c *EncodedConn) Close()

                                                                                                                                                    Close will close the connection to the server. This call will release all blocking calls, such as Flush(), etc.

                                                                                                                                                    func (*EncodedConn) Drain

                                                                                                                                                    func (c *EncodedConn) Drain() error

                                                                                                                                                      Drain will put a connection into a drain state. All subscriptions will immediately be put into a drain state. Upon completion, the publishers will be drained and can not publish any additional messages. Upon draining of the publishers, the connection will be closed. Use the ClosedCB() option to know when the connection has moved from draining to closed.

                                                                                                                                                      func (*EncodedConn) Flush

                                                                                                                                                      func (c *EncodedConn) Flush() error

                                                                                                                                                        Flush will perform a round trip to the server and return when it receives the internal reply.

                                                                                                                                                        func (*EncodedConn) FlushTimeout

                                                                                                                                                        func (c *EncodedConn) FlushTimeout(timeout time.Duration) (err error)

                                                                                                                                                          FlushTimeout allows a Flush operation to have an associated timeout.

                                                                                                                                                          func (*EncodedConn) LastError

                                                                                                                                                          func (c *EncodedConn) LastError() error

                                                                                                                                                            LastError reports the last error encountered via the Connection.

                                                                                                                                                            func (*EncodedConn) Publish

                                                                                                                                                            func (c *EncodedConn) Publish(subject string, v interface{}) error

                                                                                                                                                              Publish publishes the data argument to the given subject. The data argument will be encoded using the associated encoder.

                                                                                                                                                              Example

                                                                                                                                                                EncodedConn can publish virtually anything just by passing it in. The encoder will be used to properly encode the raw Go type

                                                                                                                                                                Output:
                                                                                                                                                                
                                                                                                                                                                

                                                                                                                                                                func (*EncodedConn) PublishRequest

                                                                                                                                                                func (c *EncodedConn) PublishRequest(subject, reply string, v interface{}) error

                                                                                                                                                                  PublishRequest will perform a Publish() expecting a response on the reply subject. Use Request() for automatically waiting for a response inline.

                                                                                                                                                                  func (*EncodedConn) QueueSubscribe

                                                                                                                                                                  func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error)

                                                                                                                                                                    QueueSubscribe will create a queue subscription on the given subject and process incoming messages using the specified Handler. The Handler should be a func that matches a signature from the description of Handler from above.

                                                                                                                                                                    func (*EncodedConn) Request

                                                                                                                                                                    func (c *EncodedConn) Request(subject string, v interface{}, vPtr interface{}, timeout time.Duration) error

                                                                                                                                                                      Request will create an Inbox and perform a Request() call with the Inbox reply for the data v. A response will be decoded into the vPtr Response.

                                                                                                                                                                      func (*EncodedConn) RequestWithContext

                                                                                                                                                                      func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v interface{}, vPtr interface{}) error

                                                                                                                                                                        RequestWithContext will create an Inbox and perform a Request using the provided cancellation context with the Inbox reply for the data v. A response will be decoded into the vPtrResponse.

                                                                                                                                                                        func (*EncodedConn) Subscribe

                                                                                                                                                                        func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error)

                                                                                                                                                                          Subscribe will create a subscription on the given subject and process incoming messages using the specified Handler. The Handler should be a func that matches a signature from the description of Handler from above.

                                                                                                                                                                          Example

                                                                                                                                                                            EncodedConn's subscribers will automatically decode the wire data into the requested Go type using the Decode() method of the registered Encoder. The callback signature can also vary to include additional data, such as subject and reply subjects.

                                                                                                                                                                            Output:
                                                                                                                                                                            
                                                                                                                                                                            

                                                                                                                                                                            type Encoder

                                                                                                                                                                            type Encoder interface {
                                                                                                                                                                            	Encode(subject string, v interface{}) ([]byte, error)
                                                                                                                                                                            	Decode(subject string, data []byte, vPtr interface{}) error
                                                                                                                                                                            }

                                                                                                                                                                              Encoder interface is for all register encoders

                                                                                                                                                                              func EncoderForType

                                                                                                                                                                              func EncoderForType(encType string) Encoder

                                                                                                                                                                                EncoderForType will return the registered Encoder for the encType.

                                                                                                                                                                                type ErrHandler

                                                                                                                                                                                type ErrHandler func(*Conn, *Subscription, error)

                                                                                                                                                                                  ErrHandler is used to process asynchronous errors encountered while processing inbound messages.

                                                                                                                                                                                  type Handler

                                                                                                                                                                                  type Handler interface{}

                                                                                                                                                                                    Handler is a specific callback used for Subscribe. It is generalized to an interface{}, but we will discover its format and arguments at runtime and perform the correct callback, including de-marshaling JSON strings back into the appropriate struct based on the signature of the Handler.

                                                                                                                                                                                    Handlers are expected to have one of four signatures.

                                                                                                                                                                                    type person struct {
                                                                                                                                                                                    	Name string `json:"name,omitempty"`
                                                                                                                                                                                    	Age  uint   `json:"age,omitempty"`
                                                                                                                                                                                    }
                                                                                                                                                                                    
                                                                                                                                                                                    handler := func(m *Msg)
                                                                                                                                                                                    handler := func(p *person)
                                                                                                                                                                                    handler := func(subject string, o *obj)
                                                                                                                                                                                    handler := func(subject, reply string, o *obj)
                                                                                                                                                                                    

                                                                                                                                                                                    These forms allow a callback to request a raw Msg ptr, where the processing of the message from the wire is untouched. Process a JSON representation and demarshal it into the given struct, e.g. person. There are also variants where the callback wants either the subject, or the subject and the reply subject.

                                                                                                                                                                                    type Msg

                                                                                                                                                                                    type Msg struct {
                                                                                                                                                                                    	Subject string
                                                                                                                                                                                    	Reply   string
                                                                                                                                                                                    	Data    []byte
                                                                                                                                                                                    	Sub     *Subscription
                                                                                                                                                                                    	// contains filtered or unexported fields
                                                                                                                                                                                    }

                                                                                                                                                                                      Msg is a structure used by Subscribers and PublishMsg().

                                                                                                                                                                                      func (*Msg) Respond

                                                                                                                                                                                      func (m *Msg) Respond(data []byte) error

                                                                                                                                                                                        Respond allows a convenient way to respond to requests in service based subscriptions.

                                                                                                                                                                                        type MsgHandler

                                                                                                                                                                                        type MsgHandler func(msg *Msg)

                                                                                                                                                                                          MsgHandler is a callback function that processes messages delivered to asynchronous subscribers.

                                                                                                                                                                                          type Option

                                                                                                                                                                                          type Option func(*Options) error

                                                                                                                                                                                            Option is a function on the options for a connection.

                                                                                                                                                                                            func ClientCert

                                                                                                                                                                                            func ClientCert(certFile, keyFile string) Option

                                                                                                                                                                                              ClientCert is a helper option to provide the client certificate from a file. If Secure is not already set this will set it as well.

                                                                                                                                                                                              func ClosedHandler

                                                                                                                                                                                              func ClosedHandler(cb ConnHandler) Option

                                                                                                                                                                                                ClosedHandler is an Option to set the closed handler.

                                                                                                                                                                                                func CustomReconnectDelay

                                                                                                                                                                                                func CustomReconnectDelay(cb ReconnectDelayHandler) Option

                                                                                                                                                                                                  CustomReconnectDelay is an Option to set the CustomReconnectDelayCB option. See CustomReconnectDelayCB Option for more details.

                                                                                                                                                                                                  func Dialer

                                                                                                                                                                                                  func Dialer(dialer *net.Dialer) Option

                                                                                                                                                                                                    Dialer is an Option to set the dialer which will be used when attempting to establish a connection. DEPRECATED: Should use CustomDialer instead.

                                                                                                                                                                                                    func DisconnectErrHandler

                                                                                                                                                                                                    func DisconnectErrHandler(cb ConnErrHandler) Option

                                                                                                                                                                                                      DisconnectErrHandler is an Option to set the disconnected error handler.

                                                                                                                                                                                                      func DisconnectHandler

                                                                                                                                                                                                      func DisconnectHandler(cb ConnHandler) Option

                                                                                                                                                                                                        DisconnectHandler is an Option to set the disconnected handler. DEPRECATED: Use DisconnectErrHandler.

                                                                                                                                                                                                        func DiscoveredServersHandler

                                                                                                                                                                                                        func DiscoveredServersHandler(cb ConnHandler) Option

                                                                                                                                                                                                          DiscoveredServersHandler is an Option to set the new servers handler.

                                                                                                                                                                                                          func DontRandomize

                                                                                                                                                                                                          func DontRandomize() Option

                                                                                                                                                                                                            DontRandomize is an Option to turn off randomizing the server pool.

                                                                                                                                                                                                            func DrainTimeout

                                                                                                                                                                                                            func DrainTimeout(t time.Duration) Option

                                                                                                                                                                                                              DrainTimeout is an Option to set the timeout for draining a connection.

                                                                                                                                                                                                              func ErrorHandler

                                                                                                                                                                                                              func ErrorHandler(cb ErrHandler) Option

                                                                                                                                                                                                                ErrorHandler is an Option to set the async error handler.

                                                                                                                                                                                                                func FlusherTimeout

                                                                                                                                                                                                                func FlusherTimeout(t time.Duration) Option

                                                                                                                                                                                                                  FlusherTimeout is an Option to set the write (and flush) timeout on a connection.

                                                                                                                                                                                                                  func MaxPingsOutstanding

                                                                                                                                                                                                                  func MaxPingsOutstanding(max int) Option

                                                                                                                                                                                                                    MaxPingsOutstanding is an Option to set the maximum number of ping requests that can go un-answered by the server before closing the connection.

                                                                                                                                                                                                                    func MaxReconnects

                                                                                                                                                                                                                    func MaxReconnects(max int) Option

                                                                                                                                                                                                                      MaxReconnects is an Option to set the maximum number of reconnect attempts.

                                                                                                                                                                                                                      func Name

                                                                                                                                                                                                                      func Name(name string) Option

                                                                                                                                                                                                                        Name is an Option to set the client name.

                                                                                                                                                                                                                        func Nkey

                                                                                                                                                                                                                        func Nkey(pubKey string, sigCB SignatureHandler) Option

                                                                                                                                                                                                                          Nkey will set the public Nkey and the signature callback to sign the server nonce.

                                                                                                                                                                                                                          func NkeyOptionFromSeed

                                                                                                                                                                                                                          func NkeyOptionFromSeed(seedFile string) (Option, error)

                                                                                                                                                                                                                            NkeyOptionFromSeed will load an nkey pair from a seed file. It will return the NKey Option and will handle signing of nonce challenges from the server. It will take care to not hold keys in memory and to wipe memory.

                                                                                                                                                                                                                            func NoCallbacksAfterClientClose

                                                                                                                                                                                                                            func NoCallbacksAfterClientClose() Option

                                                                                                                                                                                                                              NoCallbacksAfterClientClose is an Option to disable callbacks when user code calls Close(). If close is initiated by any other condition, callbacks if any will be invoked.

                                                                                                                                                                                                                              func NoEcho

                                                                                                                                                                                                                              func NoEcho() Option

                                                                                                                                                                                                                                NoEcho is an Option to turn off messages echoing back from a server. Note this is supported on servers >= version 1.2. Proto 1 or greater.

                                                                                                                                                                                                                                func NoReconnect

                                                                                                                                                                                                                                func NoReconnect() Option

                                                                                                                                                                                                                                  NoReconnect is an Option to turn off reconnect behavior.

                                                                                                                                                                                                                                  func PingInterval

                                                                                                                                                                                                                                  func PingInterval(t time.Duration) Option

                                                                                                                                                                                                                                    PingInterval is an Option to set the period for client ping commands.

                                                                                                                                                                                                                                    func ReconnectBufSize

                                                                                                                                                                                                                                    func ReconnectBufSize(size int) Option

                                                                                                                                                                                                                                      ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.

                                                                                                                                                                                                                                      func ReconnectHandler

                                                                                                                                                                                                                                      func ReconnectHandler(cb ConnHandler) Option

                                                                                                                                                                                                                                        ReconnectHandler is an Option to set the reconnected handler.

                                                                                                                                                                                                                                        func ReconnectJitter

                                                                                                                                                                                                                                        func ReconnectJitter(jitter, jitterForTLS time.Duration) Option

                                                                                                                                                                                                                                          ReconnectJitter is an Option to set the upper bound of a random delay added ReconnectWait.

                                                                                                                                                                                                                                          func ReconnectWait

                                                                                                                                                                                                                                          func ReconnectWait(t time.Duration) Option

                                                                                                                                                                                                                                            ReconnectWait is an Option to set the wait time between reconnect attempts.

                                                                                                                                                                                                                                            func RootCAs

                                                                                                                                                                                                                                            func RootCAs(file ...string) Option

                                                                                                                                                                                                                                              RootCAs is a helper option to provide the RootCAs pool from a list of filenames. If Secure is not already set this will set it as well.

                                                                                                                                                                                                                                              func Secure

                                                                                                                                                                                                                                              func Secure(tls ...*tls.Config) Option

                                                                                                                                                                                                                                                Secure is an Option to enable TLS secure connections that skip server verification by default. Pass a TLS Configuration for proper TLS. NOTE: This should NOT be used in a production setting.

                                                                                                                                                                                                                                                func SetCustomDialer

                                                                                                                                                                                                                                                func SetCustomDialer(dialer CustomDialer) Option

                                                                                                                                                                                                                                                  SetCustomDialer is an Option to set a custom dialer which will be used when attempting to establish a connection. If both Dialer and CustomDialer are specified, CustomDialer takes precedence.

                                                                                                                                                                                                                                                  func SyncQueueLen

                                                                                                                                                                                                                                                  func SyncQueueLen(max int) Option

                                                                                                                                                                                                                                                    SyncQueueLen will set the maximum queue len for the internal channel used for SubscribeSync().

                                                                                                                                                                                                                                                    func Timeout

                                                                                                                                                                                                                                                    func Timeout(t time.Duration) Option

                                                                                                                                                                                                                                                      Timeout is an Option to set the timeout for Dial on a connection.

                                                                                                                                                                                                                                                      func Token

                                                                                                                                                                                                                                                      func Token(token string) Option

                                                                                                                                                                                                                                                        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.

                                                                                                                                                                                                                                                        func TokenHandler

                                                                                                                                                                                                                                                        func TokenHandler(cb AuthTokenHandler) Option

                                                                                                                                                                                                                                                          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.

                                                                                                                                                                                                                                                          func UseOldRequestStyle

                                                                                                                                                                                                                                                          func UseOldRequestStyle() Option

                                                                                                                                                                                                                                                            UseOldRequestStyle is an Option to force usage of the old Request style.

                                                                                                                                                                                                                                                            func UserCredentials

                                                                                                                                                                                                                                                            func UserCredentials(userOrChainedFile string, seedFiles ...string) Option

                                                                                                                                                                                                                                                              UserCredentials is a convenience function that takes a filename for a user's JWT and a filename for the user's private Nkey seed.

                                                                                                                                                                                                                                                              func UserInfo

                                                                                                                                                                                                                                                              func UserInfo(user, password string) Option

                                                                                                                                                                                                                                                                UserInfo is an Option to set the username and password to use when not included directly in the URLs.

                                                                                                                                                                                                                                                                func UserJWT

                                                                                                                                                                                                                                                                func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option

                                                                                                                                                                                                                                                                  UserJWT will set the callbacks to retrieve the user's JWT and the signature callback to sign the server nonce. This an the Nkey option are mutually exclusive.

                                                                                                                                                                                                                                                                  type Options

                                                                                                                                                                                                                                                                  type Options struct {
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Url represents a single NATS server url to which the client
                                                                                                                                                                                                                                                                  	// will be connecting. If the Servers option is also set, it
                                                                                                                                                                                                                                                                  	// then becomes the first server in the Servers array.
                                                                                                                                                                                                                                                                  	Url string
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Servers is a configured set of servers which this client
                                                                                                                                                                                                                                                                  	// will use when attempting to connect.
                                                                                                                                                                                                                                                                  	Servers []string
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// NoRandomize configures whether we will randomize the
                                                                                                                                                                                                                                                                  	// server pool.
                                                                                                                                                                                                                                                                  	NoRandomize bool
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// NoEcho configures whether the server will echo back messages
                                                                                                                                                                                                                                                                  	// that are sent on this connection if we also have matching subscriptions.
                                                                                                                                                                                                                                                                  	// Note this is supported on servers >= version 1.2. Proto 1 or greater.
                                                                                                                                                                                                                                                                  	NoEcho bool
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Name is an optional name label which will be sent to the server
                                                                                                                                                                                                                                                                  	// on CONNECT to identify the client.
                                                                                                                                                                                                                                                                  	Name string
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Verbose signals the server to send an OK ack for commands
                                                                                                                                                                                                                                                                  	// successfully processed by the server.
                                                                                                                                                                                                                                                                  	Verbose bool
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Pedantic signals the server whether it should be doing further
                                                                                                                                                                                                                                                                  	// validation of subjects.
                                                                                                                                                                                                                                                                  	Pedantic bool
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Secure enables TLS secure connections that skip server
                                                                                                                                                                                                                                                                  	// verification by default. NOT RECOMMENDED.
                                                                                                                                                                                                                                                                  	Secure bool
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// TLSConfig is a custom TLS configuration to use for secure
                                                                                                                                                                                                                                                                  	// transports.
                                                                                                                                                                                                                                                                  	TLSConfig *tls.Config
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// AllowReconnect enables reconnection logic to be used when we
                                                                                                                                                                                                                                                                  	// encounter a disconnect from the current server.
                                                                                                                                                                                                                                                                  	AllowReconnect bool
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// MaxReconnect sets the number of reconnect attempts that will be
                                                                                                                                                                                                                                                                  	// tried before giving up. If negative, then it will never give up
                                                                                                                                                                                                                                                                  	// trying to reconnect.
                                                                                                                                                                                                                                                                  	MaxReconnect int
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// ReconnectWait sets the time to backoff after attempting a reconnect
                                                                                                                                                                                                                                                                  	// to a server that we were already connected to previously.
                                                                                                                                                                                                                                                                  	ReconnectWait time.Duration
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// CustomReconnectDelayCB is invoked after the library tried every
                                                                                                                                                                                                                                                                  	// URL in the server list and failed to reconnect. It passes to the
                                                                                                                                                                                                                                                                  	// user the current number of attempts. This function returns the
                                                                                                                                                                                                                                                                  	// amount of time the library will sleep before attempting to reconnect
                                                                                                                                                                                                                                                                  	// again. It is strongly recommended that this value contains some
                                                                                                                                                                                                                                                                  	// jitter to prevent all connections to attempt reconnecting at the same time.
                                                                                                                                                                                                                                                                  	CustomReconnectDelayCB ReconnectDelayHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// ReconnectJitter sets the upper bound for a random delay added to
                                                                                                                                                                                                                                                                  	// ReconnectWait during a reconnect when no TLS is used.
                                                                                                                                                                                                                                                                  	// Note that any jitter is capped with ReconnectJitterMax.
                                                                                                                                                                                                                                                                  	ReconnectJitter time.Duration
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// ReconnectJitterTLS sets the upper bound for a random delay added to
                                                                                                                                                                                                                                                                  	// ReconnectWait during a reconnect when TLS is used.
                                                                                                                                                                                                                                                                  	// Note that any jitter is capped with ReconnectJitterMax.
                                                                                                                                                                                                                                                                  	ReconnectJitterTLS time.Duration
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Timeout sets the timeout for a Dial operation on a connection.
                                                                                                                                                                                                                                                                  	Timeout time.Duration
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// DrainTimeout sets the timeout for a Drain Operation to complete.
                                                                                                                                                                                                                                                                  	DrainTimeout time.Duration
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// FlusherTimeout is the maximum time to wait for write operations
                                                                                                                                                                                                                                                                  	// to the underlying connection to complete (including the flusher loop).
                                                                                                                                                                                                                                                                  	FlusherTimeout time.Duration
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// PingInterval is the period at which the client will be sending ping
                                                                                                                                                                                                                                                                  	// commands to the server, disabled if 0 or negative.
                                                                                                                                                                                                                                                                  	PingInterval time.Duration
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// MaxPingsOut is the maximum number of pending ping commands that can
                                                                                                                                                                                                                                                                  	// be awaiting a response before raising an ErrStaleConnection error.
                                                                                                                                                                                                                                                                  	MaxPingsOut int
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// ClosedCB sets the closed handler that is called when a client will
                                                                                                                                                                                                                                                                  	// no longer be connected.
                                                                                                                                                                                                                                                                  	ClosedCB ConnHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// DisconnectedCB sets the disconnected handler that is called
                                                                                                                                                                                                                                                                  	// whenever the connection is disconnected.
                                                                                                                                                                                                                                                                  	// Will not be called if DisconnectedErrCB is set
                                                                                                                                                                                                                                                                  	// DEPRECATED. Use DisconnectedErrCB which passes error that caused
                                                                                                                                                                                                                                                                  	// the disconnect event.
                                                                                                                                                                                                                                                                  	DisconnectedCB ConnHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// DisconnectedErrCB sets the disconnected error handler that is called
                                                                                                                                                                                                                                                                  	// whenever the connection is disconnected.
                                                                                                                                                                                                                                                                  	// Disconnected error could be nil, for instance when user explicitly closes the connection.
                                                                                                                                                                                                                                                                  	// DisconnectedCB will not be called if DisconnectedErrCB is set
                                                                                                                                                                                                                                                                  	DisconnectedErrCB ConnErrHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// ReconnectedCB sets the reconnected handler called whenever
                                                                                                                                                                                                                                                                  	// the connection is successfully reconnected.
                                                                                                                                                                                                                                                                  	ReconnectedCB ConnHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// DiscoveredServersCB sets the callback that is invoked whenever a new
                                                                                                                                                                                                                                                                  	// server has joined the cluster.
                                                                                                                                                                                                                                                                  	DiscoveredServersCB ConnHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// AsyncErrorCB sets the async error handler (e.g. slow consumer errors)
                                                                                                                                                                                                                                                                  	AsyncErrorCB ErrHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// ReconnectBufSize is the size of the backing bufio during reconnect.
                                                                                                                                                                                                                                                                  	// Once this has been exhausted publish operations will return an error.
                                                                                                                                                                                                                                                                  	ReconnectBufSize int
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// SubChanLen is the size of the buffered channel used between the socket
                                                                                                                                                                                                                                                                  	// Go routine and the message delivery for SyncSubscriptions.
                                                                                                                                                                                                                                                                  	// NOTE: This does not affect AsyncSubscriptions which are
                                                                                                                                                                                                                                                                  	// dictated by PendingLimits()
                                                                                                                                                                                                                                                                  	SubChanLen int
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// UserJWT sets the callback handler that will fetch a user's JWT.
                                                                                                                                                                                                                                                                  	UserJWT UserJWTHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Nkey sets the public nkey that will be used to authenticate
                                                                                                                                                                                                                                                                  	// when connecting to the server. UserJWT and Nkey are mutually exclusive
                                                                                                                                                                                                                                                                  	// and if defined, UserJWT will take precedence.
                                                                                                                                                                                                                                                                  	Nkey string
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// SignatureCB designates the function used to sign the nonce
                                                                                                                                                                                                                                                                  	// presented from the server.
                                                                                                                                                                                                                                                                  	SignatureCB SignatureHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// User sets the username to be used when connecting to the server.
                                                                                                                                                                                                                                                                  	User string
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Password sets the password to be used when connecting to a server.
                                                                                                                                                                                                                                                                  	Password string
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Token sets the token to be used when connecting to a server.
                                                                                                                                                                                                                                                                  	Token string
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// TokenHandler designates the function used to generate the token to be used when connecting to a server.
                                                                                                                                                                                                                                                                  	TokenHandler AuthTokenHandler
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// Dialer allows a custom net.Dialer when forming connections.
                                                                                                                                                                                                                                                                  	// DEPRECATED: should use CustomDialer instead.
                                                                                                                                                                                                                                                                  	Dialer *net.Dialer
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// CustomDialer allows to specify a custom dialer (not necessarily
                                                                                                                                                                                                                                                                  	// a *net.Dialer).
                                                                                                                                                                                                                                                                  	CustomDialer CustomDialer
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// UseOldRequestStyle forces the old method of Requests that utilize
                                                                                                                                                                                                                                                                  	// a new Inbox and a new Subscription for each request.
                                                                                                                                                                                                                                                                  	UseOldRequestStyle bool
                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                  	// NoCallbacksAfterClientClose allows preventing the invocation of
                                                                                                                                                                                                                                                                  	// callbacks after Close() is called. Client won't receive notifications
                                                                                                                                                                                                                                                                  	// when Close is invoked by user code. Default is to invoke the callbacks.
                                                                                                                                                                                                                                                                  	NoCallbacksAfterClientClose bool
                                                                                                                                                                                                                                                                  }

                                                                                                                                                                                                                                                                    Options can be used to create a customized connection.

                                                                                                                                                                                                                                                                    func GetDefaultOptions

                                                                                                                                                                                                                                                                    func GetDefaultOptions() Options

                                                                                                                                                                                                                                                                      GetDefaultOptions returns default configuration options for the client.

                                                                                                                                                                                                                                                                      func (Options) Connect

                                                                                                                                                                                                                                                                      func (o Options) Connect() (*Conn, error)

                                                                                                                                                                                                                                                                        Connect will attempt to connect to a NATS server with multiple options.

                                                                                                                                                                                                                                                                        type ReconnectDelayHandler

                                                                                                                                                                                                                                                                        type ReconnectDelayHandler func(attempts int) time.Duration

                                                                                                                                                                                                                                                                          ReconnectDelayHandler is used to get from the user the desired delay the library should pause before attempting to reconnect again. Note that this is invoked after the library tried the whole list of URLs and failed to reconnect.

                                                                                                                                                                                                                                                                          type SignatureHandler

                                                                                                                                                                                                                                                                          type SignatureHandler func([]byte) ([]byte, error)

                                                                                                                                                                                                                                                                            SignatureHandler is used to sign a nonce from the server while authenticating with nkeys. The user should sign the nonce and return the raw signature. The client will base64 encode this to send to the server.

                                                                                                                                                                                                                                                                            type Statistics

                                                                                                                                                                                                                                                                            type Statistics struct {
                                                                                                                                                                                                                                                                            	InMsgs     uint64
                                                                                                                                                                                                                                                                            	OutMsgs    uint64
                                                                                                                                                                                                                                                                            	InBytes    uint64
                                                                                                                                                                                                                                                                            	OutBytes   uint64
                                                                                                                                                                                                                                                                            	Reconnects uint64
                                                                                                                                                                                                                                                                            }

                                                                                                                                                                                                                                                                              Tracks various stats received and sent on this connection, including counts for messages and bytes.

                                                                                                                                                                                                                                                                              type Status

                                                                                                                                                                                                                                                                              type Status int

                                                                                                                                                                                                                                                                                Status represents the state of the connection.

                                                                                                                                                                                                                                                                                type Subscription

                                                                                                                                                                                                                                                                                type Subscription struct {
                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                	// Subject that represents this subscription. This can be different
                                                                                                                                                                                                                                                                                	// than the received subject inside a Msg if this is a wildcard.
                                                                                                                                                                                                                                                                                	Subject string
                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                	// Optional queue group name. If present, all subscriptions with the
                                                                                                                                                                                                                                                                                	// same name will form a distributed queue, and each message will
                                                                                                                                                                                                                                                                                	// only be processed by one member of the group.
                                                                                                                                                                                                                                                                                	Queue string
                                                                                                                                                                                                                                                                                	// contains filtered or unexported fields
                                                                                                                                                                                                                                                                                }

                                                                                                                                                                                                                                                                                  A Subscription represents interest in a given subject.

                                                                                                                                                                                                                                                                                  func (*Subscription) AutoUnsubscribe

                                                                                                                                                                                                                                                                                  func (s *Subscription) AutoUnsubscribe(max int) error

                                                                                                                                                                                                                                                                                    AutoUnsubscribe will issue an automatic Unsubscribe that is processed by the server when max messages have been received. This can be useful when sending a request to an unknown number of subscribers.

                                                                                                                                                                                                                                                                                    Example
                                                                                                                                                                                                                                                                                    Output:
                                                                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                    

                                                                                                                                                                                                                                                                                    func (*Subscription) ClearMaxPending

                                                                                                                                                                                                                                                                                    func (s *Subscription) ClearMaxPending() error

                                                                                                                                                                                                                                                                                      ClearMaxPending resets the maximums seen so far.

                                                                                                                                                                                                                                                                                      func (*Subscription) Delivered

                                                                                                                                                                                                                                                                                      func (s *Subscription) Delivered() (int64, error)

                                                                                                                                                                                                                                                                                        Delivered returns the number of delivered messages for this subscription.

                                                                                                                                                                                                                                                                                        func (*Subscription) Drain

                                                                                                                                                                                                                                                                                        func (s *Subscription) Drain() error

                                                                                                                                                                                                                                                                                          Drain will remove interest but continue callbacks until all messages have been processed.

                                                                                                                                                                                                                                                                                          func (*Subscription) Dropped

                                                                                                                                                                                                                                                                                          func (s *Subscription) Dropped() (int, error)

                                                                                                                                                                                                                                                                                            Dropped returns the number of known dropped messages for this subscription. This will correspond to messages dropped by violations of PendingLimits. If the server declares the connection a SlowConsumer, this number may not be valid.

                                                                                                                                                                                                                                                                                            func (*Subscription) IsValid

                                                                                                                                                                                                                                                                                            func (s *Subscription) IsValid() bool

                                                                                                                                                                                                                                                                                              IsValid returns a boolean indicating whether the subscription is still active. This will return false if the subscription has already been closed.

                                                                                                                                                                                                                                                                                              func (*Subscription) MaxPending

                                                                                                                                                                                                                                                                                              func (s *Subscription) MaxPending() (int, int, error)

                                                                                                                                                                                                                                                                                                MaxPending returns the maximum number of queued messages and queued bytes seen so far.

                                                                                                                                                                                                                                                                                                func (*Subscription) NextMsg

                                                                                                                                                                                                                                                                                                func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error)

                                                                                                                                                                                                                                                                                                  NextMsg will return the next message available to a synchronous subscriber or block until one is available. An error is returned if the subscription is invalid (ErrBadSubscription), the connection is closed (ErrConnectionClosed), or the timeout is reached (ErrTimeout).

                                                                                                                                                                                                                                                                                                  Example
                                                                                                                                                                                                                                                                                                  Output:
                                                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                                                  

                                                                                                                                                                                                                                                                                                  func (*Subscription) NextMsgWithContext

                                                                                                                                                                                                                                                                                                  func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error)

                                                                                                                                                                                                                                                                                                    NextMsgWithContext takes a context and returns the next message available to a synchronous subscriber, blocking until it is delivered or context gets canceled.

                                                                                                                                                                                                                                                                                                    func (*Subscription) Pending

                                                                                                                                                                                                                                                                                                    func (s *Subscription) Pending() (int, int, error)

                                                                                                                                                                                                                                                                                                      Pending returns the number of queued messages and queued bytes in the client for this subscription.

                                                                                                                                                                                                                                                                                                      func (*Subscription) PendingLimits

                                                                                                                                                                                                                                                                                                      func (s *Subscription) PendingLimits() (int, int, error)

                                                                                                                                                                                                                                                                                                        PendingLimits returns the current limits for this subscription. If no error is returned, a negative value indicates that the given metric is not limited.

                                                                                                                                                                                                                                                                                                        func (*Subscription) QueuedMsgs

                                                                                                                                                                                                                                                                                                        func (s *Subscription) QueuedMsgs() (int, error)

                                                                                                                                                                                                                                                                                                          Queued returns the number of queued messages in the client for this subscription. DEPRECATED: Use Pending()

                                                                                                                                                                                                                                                                                                          func (*Subscription) SetPendingLimits

                                                                                                                                                                                                                                                                                                          func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error

                                                                                                                                                                                                                                                                                                            SetPendingLimits sets the limits for pending msgs and bytes for this subscription. Zero is not allowed. Any negative value means that the given metric is not limited.

                                                                                                                                                                                                                                                                                                            func (*Subscription) Type

                                                                                                                                                                                                                                                                                                            func (s *Subscription) Type() SubscriptionType

                                                                                                                                                                                                                                                                                                              Type returns the type of Subscription.

                                                                                                                                                                                                                                                                                                              func (*Subscription) Unsubscribe

                                                                                                                                                                                                                                                                                                              func (s *Subscription) Unsubscribe() error

                                                                                                                                                                                                                                                                                                                Unsubscribe will remove interest in the given subject.

                                                                                                                                                                                                                                                                                                                Example
                                                                                                                                                                                                                                                                                                                Output:
                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                

                                                                                                                                                                                                                                                                                                                type SubscriptionType

                                                                                                                                                                                                                                                                                                                type SubscriptionType int

                                                                                                                                                                                                                                                                                                                  SubscriptionType is the type of the Subscription.

                                                                                                                                                                                                                                                                                                                  type UserJWTHandler

                                                                                                                                                                                                                                                                                                                  type UserJWTHandler func() (string, error)

                                                                                                                                                                                                                                                                                                                    UserJWTHandler is used to fetch and return the account signed JWT for this user.

                                                                                                                                                                                                                                                                                                                    Directories

                                                                                                                                                                                                                                                                                                                    Path Synopsis
                                                                                                                                                                                                                                                                                                                    encoders
                                                                                                                                                                                                                                                                                                                    examples