launch_darkly.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. "github.com/porter-dev/porter/api/server/shared/config/envloader"
  9. )
  10. // Client is a struct wrapper around the launchdarkly client
  11. type Client struct {
  12. client *ld.LDClient
  13. }
  14. // BoolVariation returns the value of a boolean feature flag for a given evaluation context.
  15. //
  16. // Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
  17. // has no off variation.
  18. //
  19. // For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
  20. func (c Client) BoolVariation(field string, context ldcontext.Context, defaultValue bool) (bool, error) {
  21. if c.client == nil {
  22. return defaultValue, errors.New("failed to participate in launchdarkly test: no client available")
  23. }
  24. return c.client.BoolVariation(field, context, defaultValue)
  25. }
  26. // GetClient retrieves a Client for interacting with LaunchDarkly
  27. func GetClient(envConf *envloader.EnvConf) (*Client, error) {
  28. ldClient, err := ld.MakeClient(envConf.ServerConf.LaunchDarklySDKKey, 5*time.Second)
  29. if err != nil {
  30. return &Client{}, fmt.Errorf("failed to create new launchdarkly client: %w", err)
  31. }
  32. if ldClient == nil {
  33. return &Client{}, errors.New("failed to create new launchdarkly client: invalid config")
  34. }
  35. if !ldClient.Initialized() {
  36. return &Client{}, errors.New("failed to create new launchdarkly client: sdk failed to initialize")
  37. }
  38. return &Client{ldClient}, nil
  39. }