Last active
August 2, 2022 06:09
-
-
Save Ja7ad/2b55c57c7cb04a65e9e517b65b1e9baf to your computer and use it in GitHub Desktop.
nats embbeded server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"github.com/nats-io/nats-server/v2/server" | |
"github.com/nats-io/nats.go" | |
) | |
func main() { | |
opts := &server.Options{} | |
// Initialize new server with options | |
ns, err := server.NewServer(opts) | |
if err != nil { | |
panic(err) | |
} | |
// Start the server via goroutine | |
go ns.Start() | |
// Wait for server to be ready for connections | |
if !ns.ReadyForConnections(4 * time.Second) { | |
panic("not ready for connection") | |
} | |
// Connect to server | |
nc, err := nats.Connect(ns.ClientURL()) | |
if err != nil { | |
panic(err) | |
} | |
subject := "my-subject" | |
// Subscribe to the subject | |
nc.Subscribe(subject, func(msg *nats.Msg) { | |
// Print message data | |
data := string(msg.Data) | |
fmt.Println(data) | |
// Shutdown the server (optional) | |
ns.Shutdown() | |
}) | |
// Publish data to the subject | |
nc.Publish(subject, []byte("Hello embedded NATS!")) | |
// Wait for server shutdown | |
ns.WaitForShutdown() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment