launch_darkly.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package features
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
  7. ld "github.com/launchdarkly/go-server-sdk/v6"
  8. )
  9. // Client is a struct wrapper around the launchdarkly client
  10. type Client struct {
  11. Client LDClient
  12. }
  13. // LDClient is an interface that allows us to mock
  14. // the LaunchDarkly client in tests
  15. type LDClient interface {
  16. BoolVariation(key string, context ldcontext.Context, defaultVal bool) (bool, error)
  17. }
  18. // BoolVariation returns the value of a boolean feature flag for a given evaluation context.
  19. //
  20. // Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
  21. // has no off variation.
  22. //
  23. // For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
  24. func (c Client) BoolVariation(field string, context ldcontext.Context, defaultValue bool) (bool, error) {
  25. if c.Client == nil {
  26. return defaultValue, errors.New("failed to participate in launchdarkly test: no client available")
  27. }
  28. return c.Client.BoolVariation(field, context, defaultValue)
  29. }
  30. // GetClient retrieves a Client for interacting with LaunchDarkly
  31. func GetClient(launchDarklySDKKey string) (*Client, error) {
  32. ldClient, err := ld.MakeClient(launchDarklySDKKey, 5*time.Second)
  33. if err != nil {
  34. return &Client{}, fmt.Errorf("failed to create new launchdarkly client: %w", err)
  35. }
  36. if ldClient == nil {
  37. return &Client{}, errors.New("failed to create new launchdarkly client: invalid config")
  38. }
  39. if !ldClient.Initialized() {
  40. return &Client{}, errors.New("failed to create new launchdarkly client: sdk failed to initialize")
  41. }
  42. return &Client{ldClient}, nil
  43. }