ldclient

package module
v6.0.0-alpha.pub.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2022 License: Apache-2.0 Imports: 24 Imported by: 6

README

LaunchDarkly Server-side SDK for Go

Circle CI Documentation

LaunchDarkly overview

LaunchDarkly is a feature management platform that serves over 100 billion feature flags daily to help teams build better software, faster. Get started using LaunchDarkly today!

Supported Go versions

This version of the LaunchDarkly SDK has been tested with Go 1.16 and higher.

Getting started

Refer to the SDK documentation for instructions on getting started with using the SDK.

HTTPS proxy

There are two ways to specify the use of a proxy server. First, you can do it programmatically: see ldcomponents.HTTPConfiguration().

Second, Go's standard HTTP library also provides built-in support for the use of an HTTPS proxy via the HTTPS_PROXY environment variable. If this environment variable is present, then the SDK will proxy all network requests through the URL provided.

How to set the HTTPS_PROXY environment variable on Mac/Linux systems:

export HTTPS_PROXY=https://web-proxy.domain.com:8080

How to set the HTTPS_PROXY environment variable on Windows systems:

set HTTPS_PROXY=https://web-proxy.domain.com:8080

If your proxy requires authentication then you can prefix the URN with your login information:

export HTTPS_PROXY=http://user:pass@web-proxy.domain.com:8080

or

set HTTPS_PROXY=http://user:pass@web-proxy.domain.com:8080

Database integrations

Feature flag data can be kept in a persistent store using a database integration; LaunchDarkly provides integrations for several databases, such as Redis, which are provided in separate packages. See the SDK reference guide for more information.

Integration with easyjson

The SDK frequently reads and writes JSON data when it communicates with LaunchDarkly services or uses a persistent data store. By default, it uses LaunchDarkly's open-source JSON library go-jsonstream, which is considerably faster than Go's built-in encoding/json and does not depend on any third-party code. However, the SDK can optionally integrate with the third-party library easyjson, which may be even faster in some cases, without requiring any changes in your code. To enable this, set the build tag launchdarkly_easyjson when you run go build. The easyjson library is still under development and has some potential compatibility issues; see its documentation for more details.

If you do not set the launchdarkly_easyjson build tag, the SDK does not use any code from easyjson.

Learn more

Check out our documentation for in-depth instructions on configuring and using LaunchDarkly. You can also head straight to the complete reference guide for this SDK or our code-generated API documentation.

Testing

We run integration tests for all our SDKs using a centralized test harness. This approach gives us the ability to test for consistency across SDKs, as well as test networking behavior in a long-running application. These tests cover each method in the SDK, and verify that event sending, flag evaluation, stream reconnection, and other aspects of the SDK all behave correctly.

Contributing

We encourage pull requests and other contributions from the community. Check out our contributing guidelines for instructions on how to contribute to this SDK.

About LaunchDarkly

  • LaunchDarkly is a continuous delivery platform that provides feature flags as a service and allows developers to iterate quickly and safely. We allow you to easily flag your features and manage them from the LaunchDarkly dashboard. With LaunchDarkly, you can:
    • Roll out a new feature to a subset of your users (like a group of users who opt-in to a beta tester group), gathering feedback and bug reports from real-world use cases.
    • Gradually roll out a feature to an increasing percentage of users, and track the effect that the feature has on key metrics (for instance, how likely is a user to complete a purchase if they have feature A versus feature B?).
    • Turn off a feature that you realize is causing performance problems in production, without needing to re-deploy, or even restart the application with a changed configuration file.
    • Grant access to certain features based on user attributes, like payment plan (eg: users on the ‘gold’ plan get access to more features than users in the ‘silver’ plan). Disable parts of your application to facilitate maintenance, without taking everything offline.
  • LaunchDarkly provides feature flag SDKs for a wide variety of languages and technologies. Check out our documentation for a complete list.
  • Explore LaunchDarkly

Documentation

Overview

Package ldclient is the main package for the LaunchDarkly SDK.

This package contains the types and methods for the SDK client (LDClient) and its overall configuration.

Subpackages in the same repository provide additional functionality for specific features of the client. Most applications that need to change any configuration settings will use the ldcomponents package (https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v6/ldcomponents).

The SDK also uses types from the go-sdk-common.v3 repository and its subpackages (https://pkg.go.dev/github.com/launchdarkly/go-sdk-common/v3) that represent standard data structures in the LaunchDarkly model. All applications that evaluate feature flags will use the ldcontext package (https://pkg.go.dev/github.com/launchdarkly/go-sdk-common/v3/ldcontext); for some features such as custom attributes with complex data types, the ldvalue package is also helpful\ (https://pkg.go.dev/github.com/launchdarkly/go-sdk-common/v3/ldvalue)

For more information and code examples, see the Go SDK Reference: https://docs.launchdarkly.com/sdk/server-side/go

Index

Constants

View Source
const Version = internal.SDKVersion

Version is the SDK version.

Variables

View Source
var (
	// MakeClient and MakeCustomClient will return this error if the SDK was not able to establish a
	// LaunchDarkly connection within the specified time interval. In this case, the LDClient will still
	// continue trying to connect in the background.
	ErrInitializationTimeout = errors.New("timeout encountered waiting for LaunchDarkly client initialization")

	// MakeClient and MakeCustomClient will return this error if the SDK detected an error that makes it
	// impossible for a LaunchDarkly connection to succeed. Currently, the only such condition is if the
	// SDK key is invalid, since an invalid SDK key will never become valid.
	ErrInitializationFailed = errors.New("LaunchDarkly client initialization failed")

	// This error is returned by the Variation/VariationDetail methods if feature flags are not available
	// because the client has not successfully initialized. In this case, the result value will be whatever
	// default value was specified by the application.
	ErrClientNotInitialized = errors.New("feature flag evaluation called before LaunchDarkly client initialization completed") //nolint:lll
)

Initialization errors

Functions

This section is empty.

Types

type Config

type Config struct {
	// Provides configuration of the SDK's Big Segments feature.
	//
	// "Big Segments" are a specific type of user segments. For more information, read the LaunchDarkly
	// documentation about user segments: https://docs.launchdarkly.com/home/users
	//
	// If you are using this feature, you will normally specify a database implementation that matches how
	// the LaunchDarkly Relay Proxy is configured, since the Relay Proxy manages the Big Segment data.
	//
	// If nil, there is no implementation and Big Segments cannot be evaluated. In this case, any flag
	// evaluation that references a Big Segment will behave as if no users are included in any Big
	// Segments, and the EvaluationReason associated with any such flag evaluation will return
	// ldreason.BigSegmentsStoreNotConfigured from its GetBigSegmentsStatus() method.
	//
	//     // example: use Redis, with default properties
	//     import ldredis "github.com/launchdarkly/go-server-sdk-redis-redigo"
	//
	//     config.BigSegmentStore = ldcomponents.BigSegments(ldredis.DataStore())
	BigSegments interfaces.BigSegmentsConfigurationFactory

	// Sets the implementation of DataSource for receiving feature flag updates.
	//
	// If nil, the default is ldcomponents.StreamingDataSource(); see that method for an explanation of how to
	// further configure streaming behavior. Other options include ldcomponents.PollingDataSource(),
	// ldcomponents.ExternalUpdatesOnly(), ldfiledata.DataSource(), or a custom implementation for testing.
	//
	// If Offline is set to true, then DataSource is ignored.
	//
	//     // example: using streaming mode and setting streaming options
	//     config.DataSource = ldcomponents.StreamingDataSource().InitialReconnectDelay(time.Second)
	//
	//     // example: using polling mode and setting polling options
	//     config.DataSource = ldcomponents.PollingDataSource().PollInterval(time.Minute)
	//
	//     // example: specifying that data will be updated by an external process (such as the Relay Proxy)
	//     config.DataSource = ldcomponents.ExternalUpdatesOnly()
	DataSource interfaces.DataSourceFactory

	// Sets the implementation of DataStore for holding feature flags and related data received from
	// LaunchDarkly.
	//
	// If nil, the default is ldcomponents.InMemoryDataStore().
	//
	// The other option is to use a persistent data store-- that is, a database integration. These all use
	// ldcomponents.PersistentDataStore(), plus an adapter for the specific database. LaunchDarkly provides
	// adapters for several databases, as described in the Reference Guide:
	// https://docs.launchdarkly.com/sdk/concepts/data-stores
	//
	// You could also define your own database integration by implementing the PersistentDataStore interface.
	//
	//     // example: use Redis, with default properties
	//     import ldredis "github.com/launchdarkly/go-server-sdk-redis-redigo"
	//
	//     config.DataStore = ldcomponents.PersistentDataStore(ldredis.DataStore())
	DataStore interfaces.DataStoreFactory

	// Set to true to opt out of sending diagnostic events.
	//
	// Unless DiagnosticOptOut is set to true, the client will send some diagnostics data to the LaunchDarkly
	// servers in order to assist in the development of future SDK improvements. These diagnostics consist of an
	// initial payload containing some details of the SDK in use, the SDK's configuration, and the platform the
	// SDK is being run on, as well as payloads sent periodically with information on irregular occurrences such
	// as dropped events.
	DiagnosticOptOut bool

	// Sets the SDK's behavior regarding analytics events.
	//
	// If nil, the default is ldcomponents.SendEvents(); see that method for an explanation of how to further
	// configure event delivery. You may also turn off event delivery using ldcomponents.NoEvents().
	//
	// If Offline is set to true, then event delivery is always off and Events is ignored.
	//
	//     // example: enable events, flush the events every 10 seconds, buffering up to 5000 events
	//     config.Events = ldcomponents.SendEvents().FlushInterval(10 * time.Second).Capacity(5000)
	Events interfaces.EventProcessorFactory

	// Provides configuration of the SDK's network connection behavior.
	//
	// If nil, the default is ldcomponents.HTTPConfiguration(); see that method for an explanation of how to
	// further configure these options.
	//
	// If Offline is set to true, then HTTP is ignored.
	//
	//     // example: set connection timeout to 8 seconds and use a proxy server
	//     config.HTTP = ldcomponents.HTTPConfiguration().ConnectTimeout(8 * time.Second).ProxyURL(myProxyURL)
	HTTP interfaces.HTTPConfigurationFactory

	// Provides configuration of the SDK's logging behavior.
	//
	// If nil, the default is ldcomponents.Logging(); see that method for an explanation of how to
	// further configure logging behavior. The other option is ldcomponents.NoLogging().
	//
	// This example sets the minimum logging level to Warn, so Debug and Info messages will not be logged:
	//
	//     // example: enable logging only for Warn level and above
	//     // (note: ldlog is github.com/launchdarkly/go-sdk-common/v3/ldlog)
	//     config.Logging = ldcomponents.Logging().MinLevel(ldlog.Warn)
	Logging interfaces.LoggingConfigurationFactory

	// Sets whether this client is offline. An offline client will not make any network connections to LaunchDarkly,
	// and will return default values for all feature flags.
	//
	// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/offline-mode#go
	Offline bool

	// Provides configuration of custom service base URIs.
	//
	// Set this field only if you want to specify non-default values for any of the URIs. You may set
	// individual values such as Streaming, or use the helper method ldcomponents.RelayProxyEndpoints().
	//
	// The default behavior, if you do not set any of these values, is that the SDK will connect to
	// the standard endpoints in the LaunchDarkly production service. There are several use cases for
	// changing these values:
	//
	// - You are using the LaunchDarkly Relay Proxy (https://docs.launchdarkly.com/home/advanced/relay-proxy).
	// In this case, call ldcomponents.RelayProxyEndpoints and put its return value into
	// Config.ServiceEndpoints. Note that this is not the same as a regular HTTP proxy, which would
	// be set with ldcomponents.HTTPConfiguration().
	//
	//     config := ld.Config{
	//         ServiceEndpoints: ldcomponents.RelayProxyEndpoints("http://my-relay-host:8080"),
	//     }
	//
	//     // Or, if you want analytics events to be delivered directly to LaunchDarkly rather
	//     // than having them forwarded through the Relay Proxy:
	//     config := ld.Config{
	//         ServiceEndpoints: ldcomponents.RelayProxyEndpoints("http://my-relay-host:8080").
	//             WithoutEventForwarding(),
	//     }
	//
	// - You are connecting to a private instance of LaunchDarkly, rather than the standard production
	// services. In this case, there will be custom base URIs for each service, so you must set
	// Streaming, Polling, and Events to whatever URIs that have been defined for your instance.
	//
	//     config := ld.Config{
	//         ServiceEndpoints: interfaces.ServiceEndpoints{
	//             Streaming: "https://some-subdomain-a.launchdarkly.com",
	//             Polling: "https://some-subdomain-b.launchdarkly.com",
	//             Events: "https://some-subdomain-c.launchdarkly.com",
	//         },
	//     }
	//
	// - You are connecting to a test fixture that simulates the service endpoints. In this case, you
	// may set the base URIs to whatever you want, although the SDK will still set the URI paths to
	// the expected paths for LaunchDarkly services.
	ServiceEndpoints interfaces.ServiceEndpoints

	// Provides configuration of application metadata. See interfaces.ApplicationInfo.
	//
	// Application metadata may be used in LaunchDarkly analytics or other product features, but does not
	// affect feature flag evaluations.
	ApplicationInfo interfaces.ApplicationInfo
}

Config exposes advanced configuration options for the LaunchDarkly client.

All of these settings are optional, so an empty Config struct is always valid. See the description of each field for the default behavior if it is not set.

Some of the Config fields are actually factories for subcomponents of the SDK. The types of these fields are interfaces whose names end in "Factory"; the actual implementation types, which have methods for configuring that subcomponent, are normally provided by corresponding functions in the ldcomponents package (https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v6/ldcomponents). For instance, to set the Events field to a configuration in which the SDK will flush analytics events every 10 seconds:

var config ld.Config
config.Events = ldcomponents.Events().FlushInterval(time.Second * 10)

The interfaces are defined separately from the built-in component implementations because you could also define your own implementation, for custom SDK integrations.

type LDClient

type LDClient struct {
	// contains filtered or unexported fields
}

LDClient is the LaunchDarkly client.

This object evaluates feature flags, generates analytics events, and communicates with LaunchDarkly services. Applications should instantiate a single instance for the lifetime of their application and share it wherever feature flags need to be evaluated; all LDClient methods are safe to be called concurrently from multiple goroutines.

Some advanced client features are grouped together in API facades that are accessed through an LDClient method, such as GetDataSourceStatusProvider().

When an application is shutting down or no longer needs to use the LDClient instance, it should call Close() to ensure that all of its connections and goroutines are shut down and that any pending analytics events have been delivered.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/server-side/go

func MakeClient

func MakeClient(sdkKey string, waitFor time.Duration) (*LDClient, error)

MakeClient creates a new client instance that connects to LaunchDarkly with the default configuration.

For advanced configuration options, use MakeCustomClient. Calling MakeClient is exactly equivalent to calling MakeCustomClient with the config parameter set to an empty value, ld.Config{}.

Unless it is configured to be offline with Config.Offline or ldcomponents.ExternalUpdatesOnly(), the client will begin attempting to connect to LaunchDarkly as soon as you call this constructor. The constructor will return when it successfully connects, or when the timeout set by the waitFor parameter expires, whichever comes first.

If the connection succeeded, the first return value is the client instance, and the error value is nil.

If the timeout elapsed without a successful connection, it still returns a client instance-- in an uninitialized state, where feature flags will return default values-- and the error value is ErrInitializationTimeout. In this case, it will still continue trying to connect in the background.

If there was an unrecoverable error such that it cannot succeed by retrying-- for instance, the SDK key is invalid-- it will return a client instance in an uninitialized state, and the error value is ErrInitializationFailed.

If you set waitFor to zero, the function will return immediately after creating the client instance, and do any further initialization in the background.

The only time it returns nil instead of a client instance is if the client cannot be created at all due to an invalid configuration. This is rare, but could happen if for instance you specified a custom TLS certificate file that did not contain a valid certificate.

For more about the difference between an initialized and uninitialized client, and other ways to monitor the client's status, see LDClient.Initialized() and LDClient.GetDataSourceStatusProvider().

func MakeCustomClient

func MakeCustomClient(sdkKey string, config Config, waitFor time.Duration) (*LDClient, error)

MakeCustomClient creates a new client instance that connects to LaunchDarkly with a custom configuration.

The config parameter allows customization of all SDK properties; some of these are represented directly as fields in Config, while others are set by builder methods on a more specific configuration object. See Config for details.

Unless it is configured to be offline with Config.Offline or ldcomponents.ExternalUpdatesOnly(), the client will begin attempting to connect to LaunchDarkly as soon as you call this constructor. The constructor will return when it successfully connects, or when the timeout set by the waitFor parameter expires, whichever comes first.

If the connection succeeded, the first return value is the client instance, and the error value is nil.

If the timeout elapsed without a successful connection, it still returns a client instance-- in an uninitialized state, where feature flags will return default values-- and the error value is ErrInitializationTimeout. In this case, it will still continue trying to connect in the background.

If there was an unrecoverable error such that it cannot succeed by retrying-- for instance, the SDK key is invalid-- it will return a client instance in an uninitialized state, and the error value is ErrInitializationFailed.

If you set waitFor to zero, the function will return immediately after creating the client instance, and do any further initialization in the background.

The only time it returns nil instead of a client instance is if the client cannot be created at all due to an invalid configuration. This is rare, but could happen if for instance you specified a custom TLS certificate file that did not contain a valid certificate.

For more about the difference between an initialized and uninitialized client, and other ways to monitor the client's status, see LDClient.Initialized() and LDClient.GetDataSourceStatusProvider().

func (*LDClient) AllFlagsState

func (client *LDClient) AllFlagsState(context ldcontext.Context, options ...flagstate.Option) flagstate.AllFlags

AllFlagsState returns an object that encapsulates the state of all feature flags for a given evaluation. context. This includes the flag values, and also metadata that can be used on the front end.

The most common use case for this method is to bootstrap a set of client-side feature flags from a back-end service.

You may pass any combination of flagstate.ClientSideOnly, flagstate.WithReasons, and flagstate.DetailsOnlyForTrackedFlags as optional parameters to control what data is included.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/all-flags#go

func (*LDClient) BoolVariation

func (client *LDClient) BoolVariation(key string, context ldcontext.Context, defaultVal bool) (bool, error)

BoolVariation returns the value of a boolean feature flag for a given evaluation context.

Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and has no off variation.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go

func (*LDClient) BoolVariationDetail

func (client *LDClient) BoolVariationDetail(
	key string,
	context ldcontext.Context,
	defaultVal bool,
) (bool, ldreason.EvaluationDetail, error)

BoolVariationDetail is the same as BoolVariation, but also returns further information about how the value was calculated. The "reason" data will also be included in analytics events.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go

func (*LDClient) Close

func (client *LDClient) Close() error

Close shuts down the LaunchDarkly client. After calling this, the LaunchDarkly client should no longer be used. The method will block until all pending analytics events (if any) been sent.

func (*LDClient) Float64Variation

func (client *LDClient) Float64Variation(key string, context ldcontext.Context, defaultVal float64) (float64, error)

Float64Variation returns the value of a feature flag (whose variations are floats) for the given evaluation context.

Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and has no off variation.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go

func (*LDClient) Float64VariationDetail

func (client *LDClient) Float64VariationDetail(
	key string,
	context ldcontext.Context,
	defaultVal float64,
) (float64, ldreason.EvaluationDetail, error)

Float64VariationDetail is the same as Float64Variation, but also returns further information about how the value was calculated. The "reason" data will also be included in analytics events.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go

func (*LDClient) Flush

func (client *LDClient) Flush()

Flush tells the client that all pending analytics events (if any) should be delivered as soon as possible. Flushing is asynchronous, so this method will return before it is complete. However, if you call Close(), events are guaranteed to be sent before that method returns.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/flush#go

func (*LDClient) GetBigSegmentStoreStatusProvider

func (client *LDClient) GetBigSegmentStoreStatusProvider() interfaces.BigSegmentStoreStatusProvider

GetBigSegmentStoreStatusProvider returns an interface for tracking the status of a Big Segment store.

The BigSegmentStoreStatusProvider has methods for checking whether the Big Segment store is (as far as the SDK knows) currently operational and tracking changes in this status.

See the BigSegmentStoreStatusProvider interface for more about this functionality.

func (*LDClient) GetDataSourceStatusProvider

func (client *LDClient) GetDataSourceStatusProvider() interfaces.DataSourceStatusProvider

GetDataSourceStatusProvider returns an interface for tracking the status of the data source.

The data source is the mechanism that the SDK uses to get feature flag configurations, such as a streaming connection (the default) or poll requests. The DataSourceStatusProvider has methods for checking whether the data source is (as far as the SDK knows) currently operational and tracking changes in this status.

See the DataSourceStatusProvider interface for more about this functionality.

func (*LDClient) GetDataStoreStatusProvider

func (client *LDClient) GetDataStoreStatusProvider() interfaces.DataStoreStatusProvider

GetDataStoreStatusProvider returns an interface for tracking the status of a persistent data store.

The DataStoreStatusProvider has methods for checking whether the data store is (as far as the SDK knows) currently operational, tracking changes in this status, and getting cache statistics. These are only relevant for a persistent data store; if you are using an in-memory data store, then this method will always report that the store is operational.

See the DataStoreStatusProvider interface for more about this functionality.

func (*LDClient) GetFlagTracker

func (client *LDClient) GetFlagTracker() interfaces.FlagTracker

GetFlagTracker returns an interface for tracking changes in feature flag configurations.

See the FlagTracker interface for more about this functionality.

func (*LDClient) Identify

func (client *LDClient) Identify(context ldcontext.Context) error

Identify reports details about an evaluation context.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/identify#go

func (*LDClient) Initialized

func (client *LDClient) Initialized() bool

Initialized returns whether the LaunchDarkly client is initialized.

If this value is true, it means the client has succeeded at some point in connecting to LaunchDarkly and has received feature flag data. It could still have encountered a connection problem after that point, so this does not guarantee that the flags are up to date; if you need to know its status in more detail, use GetDataSourceStatusProvider.

If this value is false, it means the client has not yet connected to LaunchDarkly, or has permanently failed. See MakeClient for the reasons that this could happen. In this state, feature flag evaluations will always return default values-- unless you are using a database integration and feature flags had already been stored in the database by a successfully connected SDK in the past. You can use GetDataSourceStatusProvider to get information on errors, or to wait for a successful retry.

func (*LDClient) IntVariation

func (client *LDClient) IntVariation(key string, context ldcontext.Context, defaultVal int) (int, error)

IntVariation returns the value of a feature flag (whose variations are integers) for the given evaluation context.

Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and has no off variation.

If the flag variation has a numeric value that is not an integer, it is rounded toward zero (truncated).

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go

func (*LDClient) IntVariationDetail

func (client *LDClient) IntVariationDetail(
	key string,
	context ldcontext.Context,
	defaultVal int,
) (int, ldreason.EvaluationDetail, error)

IntVariationDetail is the same as IntVariation, but also returns further information about how the value was calculated. The "reason" data will also be included in analytics events.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go

func (*LDClient) IsOffline

func (client *LDClient) IsOffline() bool

IsOffline returns whether the LaunchDarkly client is in offline mode.

This is only true if you explicitly set the Config.Offline property to true, to force the client to be offline. It does not mean that the client is having a problem connecting to LaunchDarkly. To detect the status of a client that is configured to be online, use Initialized() or GetDataSourceStatusProvider().

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/offline-mode#go

func (*LDClient) JSONVariation

func (client *LDClient) JSONVariation(
	key string,
	context ldcontext.Context,
	defaultVal ldvalue.Value,
) (ldvalue.Value, error)

JSONVariation returns the value of a feature flag for the given evaluation context, allowing the value to be of any JSON type.

The value is returned as an ldvalue.Value, which can be inspected or converted to other types using Value methods such as GetType() and BoolValue(). The defaultVal parameter also uses this type. For instance, if the values for this flag are JSON arrays:

defaultValAsArray := ldvalue.BuildArray().
    Add(ldvalue.String("defaultFirstItem")).
    Add(ldvalue.String("defaultSecondItem")).
    Build()
result, err := client.JSONVariation(flagKey, context, defaultValAsArray)
firstItemAsString := result.GetByIndex(0).StringValue() // "defaultFirstItem", etc.

You can also use unparsed json.RawMessage values:

defaultValAsRawJSON := ldvalue.Raw(json.RawMessage(`{"things":[1,2,3]}`))
result, err := client.JSONVariation(flagKey, context, defaultValAsJSON
resultAsRawJSON := result.AsRaw()

Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go

func (*LDClient) JSONVariationDetail

func (client *LDClient) JSONVariationDetail(
	key string,
	context ldcontext.Context,
	defaultVal ldvalue.Value,
) (ldvalue.Value, ldreason.EvaluationDetail, error)

JSONVariationDetail is the same as JSONVariation, but also returns further information about how the value was calculated. The "reason" data will also be included in analytics events.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go

func (*LDClient) SecureModeHash

func (client *LDClient) SecureModeHash(context ldcontext.Context) string

SecureModeHash generates the secure mode hash value for an evaluation context.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/secure-mode#go

func (*LDClient) StringVariation

func (client *LDClient) StringVariation(key string, context ldcontext.Context, defaultVal string) (string, error)

StringVariation returns the value of a feature flag (whose variations are strings) for the given evaluation context.

Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and has no off variation.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go

func (*LDClient) StringVariationDetail

func (client *LDClient) StringVariationDetail(
	key string,
	context ldcontext.Context,
	defaultVal string,
) (string, ldreason.EvaluationDetail, error)

StringVariationDetail is the same as StringVariation, but also returns further information about how the value was calculated. The "reason" data will also be included in analytics events.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go

func (*LDClient) TrackData

func (client *LDClient) TrackData(eventName string, context ldcontext.Context, data ldvalue.Value) error

TrackData reports an event associated with an evaluation context, and adds custom data.

The eventName parameter is defined by the application and will be shown in analytics reports; it normally corresponds to the event name of a metric that you have created through the LaunchDarkly dashboard.

The data parameter is a value of any JSON type, represented with the ldvalue.Value type, that will be sent with the event. If no such value is needed, use ldvalue.Null() (or call TrackEvent instead). To send a numeric value for experimentation, use TrackMetric.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/events#go

func (*LDClient) TrackEvent

func (client *LDClient) TrackEvent(eventName string, context ldcontext.Context) error

TrackEvent reports an event associated with an evaluation context.

The eventName parameter is defined by the application and will be shown in analytics reports; it normally corresponds to the event name of a metric that you have created through the LaunchDarkly dashboard. If you want to associate additional data with this event, use TrackData or TrackMetric.

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/events#go

func (*LDClient) TrackMetric

func (client *LDClient) TrackMetric(
	eventName string,
	context ldcontext.Context,
	metricValue float64,
	data ldvalue.Value,
) error

TrackMetric reports an event associated with an evaluation context, and adds a numeric value. This value is used by the LaunchDarkly experimentation feature in numeric custom metrics, and will also be returned as part of the custom event for Data Export.

The eventName parameter is defined by the application and will be shown in analytics reports; it normally corresponds to the event name of a metric that you have created through the LaunchDarkly dashboard.

The data parameter is a value of any JSON type, represented with the ldvalue.Value type, that will be sent with the event. If no such value is needed, use ldvalue.Null().

For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/events#go

func (*LDClient) WithEventsDisabled

func (client *LDClient) WithEventsDisabled(disabled bool) interfaces.LDClientInterface

WithEventsDisabled returns a decorator for the LDClient that implements the same basic operations but will not generate any analytics events.

If events were already disabled, this is just the same LDClient. Otherwise, it is an object whose Variation methods use the same LDClient to evaluate feature flags, but without generating any events, and whose Identify/Track/Custom methods do nothing. Neither evaluation counts nor context properties will be sent to LaunchDarkly for any operations done with this object.

You can use this to suppress events within some particular area of your code where you do not want evaluations to affect your dashboard statistics, or do not want to incur the overhead of processing the events.

Note that if the original client configuration already had events disabled (config.Events = ldcomponents.NoEvents()), you cannot re-enable them with this method. It is only useful for temporarily disabling events on a client that had them enabled.

Directories

Path Synopsis
Package interfaces contains interfaces that allow customization of LaunchDarkly components, and interfaces to other advanced SDK features.
Package interfaces contains interfaces that allow customization of LaunchDarkly components, and interfaces to other advanced SDK features.
flagstate
Package flagstate contains the data types used by the LDClient.AllFlagsState() method.
Package flagstate contains the data types used by the LDClient.AllFlagsState() method.
ldstoretypes
Package ldstoretypes contains types that are only needed when implementing custom components.
Package ldstoretypes contains types that are only needed when implementing custom components.
Package internal contains SDK implementation details that are shared between packages, but are not exposed to application code.
Package internal contains SDK implementation details that are shared between packages, but are not exposed to application code.
bigsegments
Package bigsegments is an internal package containing implementation details for the SDK's Big Segment functionality, not including the part that is in go-server-sdk-evaluation.
Package bigsegments is an internal package containing implementation details for the SDK's Big Segment functionality, not including the part that is in go-server-sdk-evaluation.
datakinds
Package datakinds contains the implementations of ldstoretypes.DataKind for flags and segments.
Package datakinds contains the implementations of ldstoretypes.DataKind for flags and segments.
datasource
Package datasource is an internal package containing implementation types for the SDK's data source implementations (streaming, polling, etc.) and related functionality.
Package datasource is an internal package containing implementation types for the SDK's data source implementations (streaming, polling, etc.) and related functionality.
datastore
Package datastore is an internal package containing implementation types for the SDK's data store implementations (in-memory vs.
Package datastore is an internal package containing implementation types for the SDK's data store implementations (in-memory vs.
endpoints
Package endpoints contains internal constants and functions for computing service endpoint URIs.
Package endpoints contains internal constants and functions for computing service endpoint URIs.
sharedtest
Package sharedtest contains types and functions used by SDK unit tests in multiple packages.
Package sharedtest contains types and functions used by SDK unit tests in multiple packages.
Package ldcomponents provides the standard implementations and configuration options of LaunchDarkly components.
Package ldcomponents provides the standard implementations and configuration options of LaunchDarkly components.
ldstoreimpl
Package ldstoreimpl contains SDK data store implementation objects that may be used by external code such as custom data store integrations and internal LaunchDarkly components.
Package ldstoreimpl contains SDK data store implementation objects that may be used by external code such as custom data store integrations and internal LaunchDarkly components.
Package ldfiledata allows the LaunchDarkly client to read feature flag data from a file.
Package ldfiledata allows the LaunchDarkly client to read feature flag data from a file.
Package ldfilewatch allows the LaunchDarkly client to read feature flag data from a file that will be automatically reloaded if the file changes.
Package ldfilewatch allows the LaunchDarkly client to read feature flag data from a file that will be automatically reloaded if the file changes.
Package ldhttp provides internal helper functions for custom HTTP configuration.
Package ldhttp provides internal helper functions for custom HTTP configuration.
Package ldntlm allows you to configure the SDK to connect to LaunchDarkly through a proxy server that uses NTLM authentication.
Package ldntlm allows you to configure the SDK to connect to LaunchDarkly through a proxy server that uses NTLM authentication.
Package testhelpers contains types and functions that may be useful in testing SDK functionality or custom integrations.
Package testhelpers contains types and functions that may be useful in testing SDK functionality or custom integrations.
ldservices
Package ldservices provides HTTP handlers that simulate the behavior of LaunchDarkly service endpoints.
Package ldservices provides HTTP handlers that simulate the behavior of LaunchDarkly service endpoints.
ldtestdata
Package ldtestdata provides a mechanism for providing dynamically updatable feature flag state in a simplified form to an SDK client in test scenarios.
Package ldtestdata provides a mechanism for providing dynamically updatable feature flag state in a simplified form to an SDK client in test scenarios.
storetest
Package storetest contains the standard test suite for persistent data store implementations.
Package storetest contains the standard test suite for persistent data store implementations.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL