Skip to content

Commit

Permalink
Add godoc example for JS context functions
Browse files Browse the repository at this point in the history
Signed-off-by: Waldemar Quevedo <wally@synadia.com>
  • Loading branch information
wallyqs committed Apr 12, 2021
1 parent 192ba36 commit e7b6eda
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
36 changes: 36 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -772,3 +772,39 @@ func ExamplePullOpt() {
msg.Ack()
}
}

func ExampleContext() {
nc, err := nats.Connect("localhost")
if err != nil {
log.Fatal(err)
}

js, _ := nc.JetStream()

// Base context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// nats.Context option implements context.Context interface, so can be used
// to create a new context from top level one.
nctx := nats.Context(ctx)

// JetStreamManager functions all can use context.
js.AddStream(&nats.StreamConfig{
Name: "FOO",
Subjects: []string{"foo"},
}, nctx)

// Custom context with timeout
tctx, _ := context.WithTimeout(nctx, 2*time.Second)

// Set a timeout for publishing using context.
deadlineCtx := nats.Context(tctx)

js.Publish("foo", []byte("Hello JS!"), deadlineCtx)
sub, _ := js.SubscribeSync("foo")
msg, _ := sub.NextMsgWithContext(deadlineCtx)

// Acks can also use a context to await for a response.
msg.Ack(deadlineCtx)
}
3 changes: 2 additions & 1 deletion js.go
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,8 @@ func (ctx ContextOpt) configureAck(opts *ackOpts) error {
return nil
}

// Context returns an option that can be used to configure a context.
// Context returns an option that can be used to configure a context for APIs
// that are context aware such as those part of the JetStream interface.
func Context(ctx context.Context) ContextOpt {
return ContextOpt{ctx}
}
Expand Down

0 comments on commit e7b6eda

Please sign in to comment.