How to Use NATS for Messaging in Go

Web
Connect to a NATS server using the Go client library to publish and subscribe to messages on specific subjects.

Use the nats.go client library to connect to a NATS server, publish messages to subjects, and subscribe to receive them.

package main

import (
	"fmt"
	"log"
	"github.com/nats-io/nats.go"
)

func main() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	go func() {
		_, _ = nc.Subscribe("foo", func(msg *nats.Msg) {
			fmt.Printf("Received: %s\n", string(msg.Data))
		})
	}()

	_ = nc.Publish("foo", []byte("Hello World"))
	_ = nc.Flush()
	log.Println("Done")
}