|
| 1 | +package ldclient |
| 2 | + |
| 3 | +import "context" |
| 4 | + |
| 5 | +type scopedClientKey struct{} |
| 6 | + |
| 7 | +// GoContextWithScopedClient adds a scoped client to the Go context. This can be |
| 8 | +// used to pass a scoped client to a function or goroutine that might not |
| 9 | +// otherwise have access to it: |
| 10 | +// |
| 11 | +// scopedClient := ld.NewScopedClient(client, ldUserContext) |
| 12 | +// ctx := ld.GoContextWithScopedClient(context.Background(), scopedClient) |
| 13 | +// otherFunction(ctx) |
| 14 | +// |
| 15 | +// This function is not stable, and not subject to any backwards compatibility |
| 16 | +// guarantees or semantic versioning. It is not suitable for production usage. Do |
| 17 | +// not use it. You have been warned. |
| 18 | +func GoContextWithScopedClient(ctx context.Context, client *LDScopedClient) context.Context { |
| 19 | + return context.WithValue(ctx, scopedClientKey{}, client) |
| 20 | +} |
| 21 | + |
| 22 | +// GetScopedClient retrieves a scoped client from the Go context that was set |
| 23 | +// with GoContextWithScopedClient, if present. If not present, returns nil and |
| 24 | +// false. |
| 25 | +// |
| 26 | +// func logicWithFeatureFlag(ctx context.Context) { |
| 27 | +// scopedClient, ok := ld.GetScopedClient(ctx) |
| 28 | +// isFeatureEnabled := false // default value if scoped client is not available |
| 29 | +// if ok { |
| 30 | +// isFeatureEnabled, err = scopedClient.BoolVariation("my-flag", false) |
| 31 | +// // handle err as appropriate... |
| 32 | +// } |
| 33 | +// } |
| 34 | +// |
| 35 | +// This function is not stable, and not subject to any backwards compatibility |
| 36 | +// guarantees or semantic versioning. It is not suitable for production usage. Do |
| 37 | +// not use it. You have been warned. |
| 38 | +func GetScopedClient(ctx context.Context) (*LDScopedClient, bool) { |
| 39 | + client, ok := ctx.Value(scopedClientKey{}).(*LDScopedClient) |
| 40 | + return client, ok |
| 41 | +} |
| 42 | + |
| 43 | +// MustGetScopedClient retrieves a scoped client from the Go context that was set |
| 44 | +// with GoContextWithScopedClient, or panics if not present. |
| 45 | +// |
| 46 | +// func logicWithFeatureFlag(ctx context.Context) { |
| 47 | +// scopedClient := ld.MustGetScopedClient(ctx) |
| 48 | +// isFeatureEnabled, err := scopedClient.BoolVariation("my-flag", false) |
| 49 | +// // handle err as appropriate... |
| 50 | +// } |
| 51 | +// |
| 52 | +// This function is not stable, and not subject to any backwards compatibility |
| 53 | +// guarantees or semantic versioning. It is not suitable for production usage. Do |
| 54 | +// not use it. You have been warned. |
| 55 | +func MustGetScopedClient(ctx context.Context) *LDScopedClient { |
| 56 | + client, ok := GetScopedClient(ctx) |
| 57 | + if !ok { |
| 58 | + panic("No scoped client found in context") |
| 59 | + } |
| 60 | + return client |
| 61 | +} |
0 commit comments