Debian Codegraph @

examples/docs/learn-jetstream-publishing-confirmStored/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 confirm it was stored. A failed publish returns an
33 // error rather than losing the message silently, so check err first.
34 ack, err := js.Publish(ctx, "orders.created", []byte(payload))
35 if err != nil {
36 panic(err)
37 }
38
39 // The returned PubAck is proof the message is on disk in the stream.
40 fmt.Printf("Stored in %s at sequence %d\n", ack.Stream, ack.Sequence)
41 // NATS-DOC-END
42 }