Skip to content

Commit

Permalink
Merge pull request #710 from wallyqs/godoc-context-example
Browse files Browse the repository at this point in the history
Add godoc example for JS context functions
  • Loading branch information
kozlovic committed May 3, 2021
2 parents 1667213 + a2f745a commit ea036d7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
37 changes: 37 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -774,3 +774,40 @@ 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, tcancel := context.WithTimeout(nctx, 2*time.Second)
defer tcancel()

// 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 @@ -775,7 +775,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 ea036d7

Please sign in to comment.