1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package test
- import (
- "fmt"
- "github.com/nats-io/nats-server/v2/server"
- "github.com/nats-io/nats.go"
- "testing"
- "time"
- )
- func TestNats_server(t *testing.T) {
- opts := &server.Options{
- ServerName: "Yunlot-nats-server",
- Port: 6503,
- }
- // Initialize new server with options
- ns, err := server.NewServer(opts)
- if err != nil {
- panic(any(err))
- }
- // Start the server via goroutine
- go ns.Start()
- // Wait for server to be ready for connections
- if !ns.ReadyForConnections(4 * time.Second) {
- panic(any("not ready for connection"))
- }
- // Connect to server
- nc, err := nats.Connect(ns.ClientURL())
- if err != nil {
- panic(any(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()
- }
|