Skip to content

Instantly share code, notes, and snippets.

@oddmario
Created May 4, 2026 16:03
Show Gist options
  • Select an option

  • Save oddmario/8ee1806fd69029e5e08fb76ec7d7e694 to your computer and use it in GitHub Desktop.

Select an option

Save oddmario/8ee1806fd69029e5e08fb76ec7d7e694 to your computer and use it in GitHub Desktop.
Example code for a NATS server and client in Go
package main
import (
"fmt"
"log"
"time"
natsServer "github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
)
var natsClientOpts []nats.Option = []nats.Option{
nats.Token("super_secret_internal_token_123!@#"),
nats.RetryOnFailedConnect(true),
// Try to reconnect indefinitely (don't give up if the main server is down for a while)
nats.MaxReconnects(-1),
// Wait 2 seconds between reconnect attempts
nats.ReconnectWait(2 * time.Second),
// Optional: Log when a disconnect happens
nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
log.Printf("Disconnected from NATS! Reason: %v\n", err)
}),
// Optional: Log when the connection is successfully restored
nats.ReconnectHandler(func(nc *nats.Conn) {
log.Printf("Reconnected to NATS at %s!\n", nc.ConnectedUrl())
}),
}
func client() {
// Connect to the Main Server's IP where NATS is embedded
// This opens EXACTLY ONE persistent TCP connection
nc, err := nats.Connect("nats://127.0.0.1:4222", natsClientOpts...)
if err != nil {
log.Fatalf("Failed to connect to NATS: %v", err)
}
defer nc.Close()
// Simulate sending a request to the main server
// NATS handles the multiplexing, so you can call this concurrently
// thousands of times without opening new TCP connections.
go func() {
msg1, err1 := nc.Request("api.requests", []byte("Hello from Load Balancer 1"), 2*time.Second)
if err1 != nil {
log.Fatalf("Request failed: %v", err1)
}
fmt.Printf("Reply for LB 1: %s\n", string(msg1.Data))
}()
go func() {
msg2, err2 := nc.Request("api.requests", []byte("Hello from Load Balancer 2"), 2*time.Second)
if err2 != nil {
log.Fatalf("Request failed: %v", err2)
}
fmt.Printf("Reply for LB 2: %s\n", string(msg2.Data))
}()
select {}
}
func main() {
// 1. Configure the embedded NATS server
opts := &natsServer.Options{
Host: "0.0.0.0", // Listen on all interfaces so the LB can connect
Port: 4222, // Default NATS port
Authorization: "super_secret_internal_token_123!@#",
// You can add advanced authorization, TLS, etc., in these options
}
// 2. Initialize the server
ns, err := natsServer.NewServer(opts)
if err != nil {
log.Fatalf("Failed to initialize NATS server: %v", err)
}
// 3. Start the server in the background
ns.Start() // this is a non-blocking method
defer ns.Shutdown()
// 4. Wait for the server to be ready to accept connections
if !ns.ReadyForConnections(10 * time.Second) {
log.Fatal("NATS server failed to start")
}
fmt.Println("Embedded NATS server started on port 4222")
// ---
// At this point, your NATS server is running.
// Now, let's connect your main application logic to it.
// ---
// Connect the main app to its own embedded broker
nc, err := nats.Connect(ns.ClientURL(), natsClientOpts...)
if err != nil {
log.Fatalf("Failed to connect to embedded NATS: %v", err)
}
defer nc.Close()
// Subscribe to a topic to listen for Load Balancer messages
nc.Subscribe("api.requests", func(m *nats.Msg) {
fmt.Printf("Received message from Load Balancer: %s\n", string(m.Data))
// Send a reply back to the Load Balancer over the same single connection
m.Respond(m.Data)
})
go client()
// Keep your main server running
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment