...
1 package featureflag
2
3 import (
4 "errors"
5 "os"
6 "time"
7
8 "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
9 ld "github.com/launchdarkly/go-server-sdk/v6"
10 )
11
12 var (
13 client *ld.LDClient
14
15 recreateClient bool
16 config ld.Config
17 )
18
19 var ErrNoAPIKey = errors.New("LD_KEY not set")
20
21 func Client() (*ld.LDClient, error) {
22 if client != nil && !recreateClient {
23 return client, nil
24 }
25 recreateClient = false
26
27
28
29 key, hasKey := os.LookupEnv("LD_KEY")
30 if !hasKey && config.DataSource == nil {
31 return nil, ErrNoAPIKey
32 }
33 var err error
34 client, err = ld.MakeCustomClient(key, config, 10*time.Second)
35 return client, err
36 }
37
38 func SetConfig(c ld.Config) {
39 recreateClient = true
40 config = c
41 }
42
43
44
45 func FeatureEnabledForContext(ctxer Contextualizer, feature string, defaultVal bool) (bool, error) {
46 client, err := Client()
47 if err != nil {
48 return defaultVal, err
49 }
50 ldCtx := ldcontext.NewWithKind(ctxer.Kind(), ctxer.Key())
51 return client.BoolVariation(feature, ldCtx, defaultVal)
52 }
53
54
55
56 func FeatureEnabledForBanner(feature, banner string, defaultVal bool) (bool, error) {
57 return FeatureEnabledForContext(NewBannerContext(banner), feature, defaultVal)
58 }
59
60
61
62 func FeatureEnabledForLDContext(feature string, ldcontext ldcontext.Context, defaultVal bool) (bool, error) {
63 client, err := Client()
64 if err != nil {
65 return defaultVal, err
66 }
67 return client.BoolVariation(feature, ldcontext, defaultVal)
68 }
69
70
71
72 func FeatureEnabled(feature string, defaultVal bool) (bool, error) {
73 return FeatureEnabledForContext(NewEnvironmentContext(), feature, defaultVal)
74 }
75
View as plain text