-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext.go
More file actions
50 lines (39 loc) · 1.1 KB
/
context.go
File metadata and controls
50 lines (39 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package bee
import (
"context"
"github.com/nats-io/nats.go"
)
type key[T any] string
func with[T any](ctx context.Context, k key[T], v T) context.Context {
return context.WithValue(ctx, k, v)
}
func get[T any](ctx context.Context, k key[T]) (T, bool) {
v, ok := ctx.Value(k).(T)
return v, ok
}
var natsKey = key[*nats.Conn]("natsKey")
// WithNats adds a NATS connection to the context.
func WithNats(ctx context.Context, nc *nats.Conn) context.Context {
return with(ctx, natsKey, nc)
}
// Nats retrieves the NATS connection from the context.
func Nats(ctx context.Context) (*nats.Conn, bool) {
nc, ok := get(ctx, natsKey)
if !ok {
return nil, false
}
return nc, true
}
var jsKey = key[nats.JetStreamContext]("jsKey")
// WithJetStream adds a JetStream context to the context.
func WithJetStream(ctx context.Context, js nats.JetStreamContext) context.Context {
return with(ctx, jsKey, js)
}
// JetStream retrieves the JetStream context from the context.
func JetStream(ctx context.Context) (nats.JetStreamContext, bool) {
js, ok := get(ctx, jsKey)
if !ok {
return nil, false
}
return js, true
}