-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathldclient_gocontext.go
More file actions
61 lines (56 loc) · 2.23 KB
/
Copy pathldclient_gocontext.go
File metadata and controls
61 lines (56 loc) · 2.23 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
51
52
53
54
55
56
57
58
59
60
61
package ldclient
import "context"
type scopedClientKey struct{}
// GoContextWithScopedClient adds a scoped client to the Go context. This can be
// used to pass a scoped client to a function or goroutine that might not
// otherwise have access to it:
//
// scopedClient := ld.NewScopedClient(client, ldUserContext)
// ctx := ld.GoContextWithScopedClient(context.Background(), scopedClient)
// otherFunction(ctx)
//
// This function is in beta. It is still undergoing testing and active
// development. Its functionality may change without notice, including becoming
// backwards incompatible.
func GoContextWithScopedClient(ctx context.Context, client *LDScopedClient) context.Context {
return context.WithValue(ctx, scopedClientKey{}, client)
}
// GetScopedClient retrieves a scoped client from the Go context that was set
// with GoContextWithScopedClient, if present. If not present, returns nil and
// false.
//
// func logicWithFeatureFlag(ctx context.Context) {
// scopedClient, ok := ld.GetScopedClient(ctx)
// isFeatureEnabled := false // default value if scoped client is not available
// if ok {
// isFeatureEnabled, err = scopedClient.BoolVariation("my-flag", false)
// // handle err as appropriate...
// }
// }
//
// This function is in beta. It is still undergoing testing and active
// development. Its functionality may change without notice, including becoming
// backwards incompatible.
func GetScopedClient(ctx context.Context) (*LDScopedClient, bool) {
client, ok := ctx.Value(scopedClientKey{}).(*LDScopedClient)
return client, ok
}
// MustGetScopedClient retrieves a scoped client from the Go context that was set
// with GoContextWithScopedClient, or panics if not present.
//
// func logicWithFeatureFlag(ctx context.Context) {
// scopedClient := ld.MustGetScopedClient(ctx)
// isFeatureEnabled, err := scopedClient.BoolVariation("my-flag", false)
// // handle err as appropriate...
// }
//
// This function is in beta. It is still undergoing testing and active
// development. Its functionality may change without notice, including becoming
// backwards incompatible.
func MustGetScopedClient(ctx context.Context) *LDScopedClient {
client, ok := GetScopedClient(ctx)
if !ok {
panic("No scoped client found in context")
}
return client
}