Skip to content

Instantly share code, notes, and snippets.

@treeder
Last active September 13, 2019 17:29
Show Gist options
  • Save treeder/21cb19d183d6a3ee5785e387b75fe35e to your computer and use it in GitHub Desktop.
Save treeder/21cb19d183d6a3ee5785e387b75fe35e to your computer and use it in GitHub Desktop.
Nats example
package main
import (
"encoding/json"
"fmt"
"log"
"sync"
nats "github.com/nats-io/nats.go"
)
// Order is the structure of the messages we'll be sending and receiving
type Order struct {
ID string `json:"id"`
Amount float64 `json:"amount"`
}
func main() {
// Connect to Nats server
c, err := nats.Connect("nats://localhost:4222")
if err != nil {
log.Fatal(err)
}
defer c.Close()
// The channel we'll be publishing and subscribing too
channel := "orders"
numMessages := 10
var wg sync.WaitGroup
// Subscribe: we subscribe first so we get all published messages
_, err = c.Subscribe(channel, func(m *nats.Msg) {
order := &Order{}
err := json.Unmarshal(m.Data, order)
if err != nil {
fmt.Printf("Unmarshal error: %v\n", err)
// todo: be nice to have a way for user to deal with errors
return
}
fmt.Printf("got order: %+v\n", order)
wg.Done()
})
if err != nil {
log.Fatal(err)
}
// Publish: Now we publish messages to the channel we subscribed to above
for i := 0; i < numMessages; i++ {
order := &Order{ID: fmt.Sprintf("%v", i+1), Amount: 101.01}
b, err := json.Marshal(order)
if err != nil {
log.Fatal(err)
}
if err := c.Publish(channel, b); err != nil {
log.Fatal(err)
}
wg.Add(1)
}
// Make sure the message goes through before we close
c.Flush()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment