package featureflag import ( "errors" "os" "time" "github.com/launchdarkly/go-sdk-common/v3/ldcontext" ld "github.com/launchdarkly/go-server-sdk/v6" ) var ( client *ld.LDClient recreateClient bool // this is set to true whenever the SetConfig function is called. config ld.Config ) var ErrNoAPIKey = errors.New("LD_KEY not set") func Client() (*ld.LDClient, error) { if client != nil && !recreateClient { return client, nil } recreateClient = false // if no LD_KEY is given, then a custom data source is required, // The custom data source is set when testing using the testutil package. key, hasKey := os.LookupEnv("LD_KEY") if !hasKey && config.DataSource == nil { return nil, ErrNoAPIKey } var err error client, err = ld.MakeCustomClient(key, config, 10*time.Second) return client, err } func SetConfig(c ld.Config) { recreateClient = true config = c } // FeatureEnabledForContext wraps BoolVariation to get the value of a boolean // feature flag for a particular LD Context. func FeatureEnabledForContext(ctxer Contextualizer, feature string, defaultVal bool) (bool, error) { client, err := Client() if err != nil { return defaultVal, err } ldCtx := ldcontext.NewWithKind(ctxer.Kind(), ctxer.Key()) return client.BoolVariation(feature, ldCtx, defaultVal) } // FeatureEnabledForBanner is a helper wrapping [FeatureEnabledForContext] that automatically creates a // [BannerContext]. func FeatureEnabledForBanner(feature, banner string, defaultVal bool) (bool, error) { return FeatureEnabledForContext(NewBannerContext(banner), feature, defaultVal) } // FeatureEnabledForLDContext wraps BoolVariation to get the value of a boolean // feature flag for a particular LD Context. func FeatureEnabledForLDContext(feature string, ldcontext ldcontext.Context, defaultVal bool) (bool, error) { client, err := Client() if err != nil { return defaultVal, err } return client.BoolVariation(feature, ldcontext, defaultVal) } // FeatureEnabled is a helper wrapping FeatureEnabledForContext that automatically creates an // EnvironmentContext, which is a rule not targeted to a specific Context. func FeatureEnabled(feature string, defaultVal bool) (bool, error) { return FeatureEnabledForContext(NewEnvironmentContext(), feature, defaultVal) }