Nats
A NATS Key/Value storage driver.
Table of Contents
Signatures
func New(config ...Config) Storage
func NewWithContext(ctx context.Context, config ...Config) *Storage
func NewFromConnection(nc *nats.Conn, config ...Config) *Storage
func NewFromConnectionWithContext(ctx context.Context, nc *nats.Conn, config ...Config) *Storage
func (s *Storage) Get(key string) ([]byte, error)
func (s *Storage) GetWithContext(ctx context.Context, key string) ([]byte, error)
func (s *Storage) Set(key string, val []byte, exp time.Duration) error
func (s *Storage) SetWithContext(ctx context.Context, key string, val []byte, exp time.Duration) error
func (s *Storage) Delete(key string) error
func (s *Storage) DeleteWithContext(ctx context.Context, key string) error
func (s *Storage) Reset() error
func (s *Storage) ResetWithContext(ctx context.Context) error
func (s *Storage) Close() error
func (s *Storage) Conn() (*nats.Conn, jetstream.KeyValue)
func (s *Storage) Keys() ([]string, error)
Note: Expirations are stored with a one-second granularity and rounded up, so an entry is never dropped before its expiration but may outlive it by up to a second.
Note: An expired entry is never returned, but the driver deletes it only when that key is read again (a small delete marker stays in the bucket), and the default bucket has no age limit. If every entry you store has an expiration, set KeyValueConfig.TTL to at least the longest one so the server drops the rest; it applies to all entries, including those stored without an expiration. An existing bucket keeps its settings, so change its TTL with js.UpdateKeyValue (pass the bucket's full KeyValueConfig) or the nats CLI on stream KV_<bucket>.
Note: Keys must be valid NATS KV keys. A key longer than about 3,900 bytes (less for a long bucket name or inbox prefix) is refused with jetstream.ErrInvalidKey, since nats-server closes the connection on a protocol line over its default max_control_line of 4096 bytes. The limit assumes that default: a higher server value does not raise it, and a lower one closes the connection on shorter keys too. A longer key written by an earlier version cannot be deleted through this driver; use Reset, the bucket TTL or the KV handle from Conn().
Installation
NATS Key/Value Store driver is tested on the 2 last Go versions with support for modules. So make sure to initialize one first if you didn't do that yet:
go mod init github.com/<user>/<repo>
And then install the nats implementation:
go get github.com/gofiber/storage/nats
Examples
Import the storage package.
import "github.com/gofiber/storage/nats"
You can use the following options to create a storage driver:
// Initialize default config
store := nats.New()
// Initialize custom config
store := nats.New(Config{
URLs: "nats://127.0.0.1:4443",
NatsOptions: []nats.Option{
nats.MaxReconnects(2),
// Enable TLS by specifying RootCAs
nats.RootCAs("./testdata/certs/ca.pem"),
},
KeyValueConfig: jetstream.KeyValueConfig{
Bucket: "test",
Storage: jetstream.MemoryStorage,
},
})
Config
type Config struct {
// Nats URLs, default "nats://127.0.0.1:4222". Can be comma separated list for multiple servers
URLs string
// Nats connection options. See nats_test.go for an example of how to use this.
NatsOptions []nats.Option
// Nats connection name
ClientName string
// Nats context
Context context.Context
// Nats key value config
KeyValueConfig jetstream.KeyValueConfig
// Wait for connection to be established, default: 250ms
WaitForConnection time.Duration
// Reset clears any existing keys in existing bucket default: false
Reset bool
}
Default Config
var ConfigDefault = Config{
URLs: nats.DefaultURL,
Context: context.Background(),
ClientName: "fiber_storage",
KeyValueConfig: jetstream.KeyValueConfig{
Bucket: "fiber_storage",
},
WaitForConnection: 100 * time.Millisecond,
}
Using an Existing NATS Connection
If your application already holds a *nats.Conn, you can build the storage on it instead of connecting a second time. Only the KeyValueConfig and Reset options are read; the connection settings come from the connection. Your own connect and reconnect handlers are left alone.
The connection stays yours to close: Close on a storage built this way leaves it open, so the rest of your application keeps working.
Because no handlers are installed, the bucket is resolved lazily: an operation retries the setup when the bucket is still missing, and re-resolves it if its backing stream disappears. A bucket this driver created is recreated should it vanish; a bucket that already existed is only looked up again, so one your application configured — with its own history, TTL and replica settings — is never silently replaced by this driver's defaults.
import (
"github.com/gofiber/storage/nats"
natsgo "github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
func main() {
nc, err := natsgo.Connect("nats://127.0.0.1:4222")
if err != nil {
panic(err)
}
defer nc.Close()
store := nats.NewFromConnection(nc, nats.Config{
KeyValueConfig: jetstream.KeyValueConfig{
Bucket: "fiber_storage",
},
})
defer store.Close()
}