Debian Codegraph @

examples/docs/learn-core-nats-request-reply-replies/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 // Gather more than one reply to a single request. A plain Request returns
19 // only the first reply, so when several services may answer, subscribe to
20 // your own inbox, publish the request with that inbox as the reply subject,
21 // and collect replies until they stop arriving.
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("orders.inventory.check", inbox, []byte(order))
26
27 var replies [][]byte
28 for {
29 // Stop once no further reply arrives within the gap deadline.
30 msg, err := sub.NextMsg(300 * time.Millisecond)
31 if err != nil {
32 break
33 }
34 replies = append(replies, msg.Data)
35 }
36 fmt.Printf("gathered %d replies\n", len(replies))
37 // NATS-DOC-END
38 }