Debian Codegraph @

examples/docs/learn-jetstream-publishing-pubAck/main.go

raw
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "time"
7
8 "github.com/nats-io/nats.go"
9 "github.com/nats-io/nats.go/jetstream"
10 )
11
12 func main() {
13 // Connect to the NATS server.
14 nc, err := nats.Connect("nats://localhost:4222")
15 if err != nil {
16 panic(err)
17 }
18 defer nc.Close()
19
20 // Create a JetStream context (the stream manager).
21 js, err := jetstream.New(nc)
22 if err != nil {
23 panic(err)
24 }
25
26 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
27 defer cancel()
28
29 payload := `{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}`
30
31 // NATS-DOC-START
32 // Publish one order and inspect the PubAck the server returns.
33 ack, err := js.Publish(ctx, "orders.created", []byte(payload))
34 if err != nil {
35 panic(err)
36 }
37
38 // The PubAck confirms which stream stored the message, at what sequence,
39 // and whether it was treated as a duplicate.
40 fmt.Printf("Stream: %s\n", ack.Stream)
41 fmt.Printf("Sequence: %d\n", ack.Sequence)
42 fmt.Printf("Duplicate: %t\n", ack.Duplicate)
43 // NATS-DOC-END
44 }