MCPcopy
hub / github.com/nats-io/nats.go / ExampleContext

Function ExampleContext

example_test.go:762–797  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

760}
761
762func ExampleContext() {
763 nc, err := nats.Connect("localhost")
764 if err != nil {
765 log.Fatal(err)
766 }
767
768 js, _ := nc.JetStream()
769
770 // Base context
771 ctx, cancel := context.WithCancel(context.Background())
772 defer cancel()
773
774 // nats.Context option implements context.Context interface, so can be used
775 // to create a new context from top level one.
776 nctx := nats.Context(ctx)
777
778 // JetStreamManager functions all can use context.
779 js.AddStream(&nats.StreamConfig{
780 Name: "FOO",
781 Subjects: []string{"foo"},
782 }, nctx)
783
784 // Custom context with timeout
785 tctx, tcancel := context.WithTimeout(nctx, 2*time.Second)
786 defer tcancel()
787
788 // Set a timeout for publishing using context.
789 deadlineCtx := nats.Context(tctx)
790
791 js.Publish("foo", []byte("Hello JS!"), deadlineCtx)
792 sub, _ := js.SubscribeSync("foo")
793 msg, _ := sub.NextMsgWithContext(deadlineCtx)
794
795 // Acks can also use a context to await for a response.
796 msg.Ack(deadlineCtx)
797}

Callers

nothing calls this directly

Calls 8

ConnectMethod · 0.80
JetStreamMethod · 0.80
NextMsgWithContextMethod · 0.80
ContextMethod · 0.65
AddStreamMethod · 0.65
PublishMethod · 0.65
SubscribeSyncMethod · 0.65
AckMethod · 0.65

Tested by

no test coverage detected