Debian Codegraph @

examples/docs/learn-core-nats-scatter-gather-gather/main.go

raw
1 package main
2
3 import (
4 "fmt"
5 "time"
6
7 "github.com/nats-io/nats.go"
8 )
9
10 func main() {
11 nc, err := nats.Connect(nats.DefaultURL)
12 if err != nil {
13 panic(err)
14 }
15 defer nc.Close()
16
17 // NATS-DOC-START
18 // Scatter one request to every shipping-quote provider and gather the
19 // replies. Subscribe to a private inbox, publish the request with that
20 // inbox as the reply subject, then collect quotes until they stop arriving
21 // and pick the cheapest.
22 order := `{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}`
23 inbox := nats.NewInbox()
24 sub, _ := nc.SubscribeSync(inbox)
25 nc.PublishRequest("shipping.quote", inbox, []byte(order))
26
27 var quotes []string
28 for {
29 msg, err := sub.NextMsg(300 * time.Millisecond)
30 if err != nil {
31 break
32 }
33 quotes = append(quotes, string(msg.Data))
34 }
35 fmt.Printf("gathered %d quotes: %v\n", len(quotes), quotes)
36 // NATS-DOC-END
37 }