Skip to content

Instantly share code, notes, and snippets.

@kaustavdm
Last active November 11, 2024 16:29
Show Gist options
  • Save kaustavdm/73560c70744cc5e08f3d08cc43a8f6af to your computer and use it in GitHub Desktop.
Save kaustavdm/73560c70744cc5e08f3d08cc43a8f6af to your computer and use it in GitHub Desktop.
Embed NATS in Go
package main
import (
"flag"
"log"
"github.com/nats-io/nats-server/v2/server"
nats "github.com/nats-io/nats.go"
)
func main() {
// Declare CLI Flags
embedNats := flag.Bool("embed-nats", true, "Start NATS as an embedded server")
natsIPC := flag.Bool("nats-ipc", true, "Disable network interface for embedded NATS server and connect over inter-process communication (IPC).")
// Parse CLI flags
flag.Parse()
var nc *nats.Conn
var ns *server.Server
var err error
if *embedNats {
// Start NATS embedded server
nc, ns, err = core.EmbedNats(core.NatsOpts{
ServerName: "embeded-nats",
ClientName: "embedded-nats-client",
JetStream: true,
JetStreamDomain: "example",
IPC: *natsIPC,
Logging: true,
})
defer ns.WaitForShutdown()
if err != nil {
log.Fatal(err)
}
}
nc.Subscribe("u.system.test", func(m *nats.Msg) {
m.Respond([]byte("Hi there!"))
})
}
package core
import (
"time"
server "github.com/nats-io/nats-server/v2/server"
nats "github.com/nats-io/nats.go"
)
// Configuration options for NATS server and conn
type NatsOpts struct {
// Name of the NATS server
ServerName string
// Name of the client for NATS
ClientName string
// Enable JetStream
JetStream bool
// Jetstream domain, e.g., "upspeak"
JetStreamDomain string
// Connect to NATS Server through Inter-Process Communication
IPC bool
// Enable logging for the embedded nats server
Logging bool
}
// Start an embedded NATS server and create a NATS client
// See: https://www.youtube.com/watch?v=cdTrl8UfcBo
func EmbedNats(opts NatsOpts) (*nats.Conn, *server.Server, error) {
serverOpts := &server.Options{
ServerName: opts.ServerName,
DontListen: opts.IPC,
JetStream: opts.JetStream,
JetStreamDomain: opts.JetStreamDomain,
}
ns, err := server.NewServer(serverOpts)
if err != nil {
return nil, nil, err
}
if opts.Logging {
ns.ConfigureLogger()
}
ns.Start()
if !ns.ReadyForConnections(5 * time.Second) {
return nil, nil, nats.ErrTimeout
}
clientOpts := []nats.Option{
nats.Name(opts.ClientName),
}
if opts.IPC {
clientOpts = append(clientOpts, nats.InProcessServer(ns))
}
nc, err := nats.Connect(nats.DefaultURL, clientOpts...)
if err != nil {
return nil, nil, err
}
return nc, ns, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment