ldclient

package module
v6.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2023 License: Apache-2.0 Imports: 25 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 requires a Go version of 1.18 or 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 (Config).

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 package github.com/launchdarkly/go-server-sdk/v6/ldcomponents.

The SDK also uses types from the go-sdk-common repository and its subpackages ([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 (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 (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
	//
	// To enable Big Segments, set this field to the configuration builder that is returned by
	// ldcomponents.BigSegments(), which allows you to specify what database to use as well as other
	// options.
	//
	// 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.BigSegmentStore())
	BigSegments subsystems.ComponentConfigurer[subsystems.BigSegmentsConfiguration]

	// Sets the implementation of DataSource for receiving feature flag updates.
	//
	// If Offline is set to true, then DataSource is ignored.
	//
	// The interface type for this field allows you to set it to any of the following:
	//   - ldcomponents.StreamingDataSource(), which enables streaming data and provides a builder to further
	//     configure streaming behavior.
	//   - ldcomponents.PollingDataSource(), which turns off streaming, enables polling, and provides a builder
	//     to further configure polling behavior.
	//   - ldcomponents.ExternalUpdatesOnly(), which turns off all data sources unless an external process is
	//     providing data via a database.
	//   - ldfiledata.DataSource() or ldtestdata.DataSource(), which provide configurable local data sources
	//     for testing.
	//   - Or, a custom component that implements ComponentConfigurer[DataSource].
	//
	//     // 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 subsystems.ComponentConfigurer[subsystems.DataSource]

	// 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 subsystems.ComponentConfigurer[subsystems.DataStore]

	// 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.
	//
	// The interface type for this field allows you to set it to either:
	//   - ldcomponents.SendEvents(), a configuration builder that allows you to customize event behavior;
	//   - ldcomponents.NoEvents(), which turns off event delivery.
	//
	// If this field is unset/nil, the default is ldcomponents.SendEvents() with no custom options.
	//
	// 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 subsystems.ComponentConfigurer[ldevents.EventProcessor]

	// Provides configuration of the SDK's network connection behavior.
	//
	// The interface type used here is implemented by ldcomponents.HTTPConfigurationBuilder, which
	// you can create by calling ldcomponents.HTTPConfiguration(). See that method for an explanation
	// of how to configure the builder. If nil, the default is ldcomponents.HTTPConfiguration() with
	// no custom settings.
	//
	// 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 subsystems.ComponentConfigurer[subsystems.HTTPConfiguration]

	// Provides configuration of the SDK's logging behavior.
	//
	// The interface type used here is implemented by ldcomponents.LoggingConfigurationBuilder, which
	// you can create by calling ldcomponents.Logging(). See that method for an explanation of how to
	// configure the builder. If nil, the default is ldcomponents.Logging() with no custom settings.
	// You can also set this field to ldcomponents.NoLogging() to disable all logging.
	//
	// 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 subsystems.ComponentConfigurer[subsystems.LoggingConfiguration]

	// 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 LDClient.

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 simple types, but others contain configuration builders for subcomponents of the SDK. When these are represented by the ComponentConfigurer interface, the actual implementation types are provided by corresponding functions in the ldcomponents package. 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 LDClient.GetDataSourceStatusProvider.

When an application is shutting down or no longer needs to use the LDClient instance, it should call LDClient.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{}.

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 LDClient.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 LDClient.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. This flush is asynchronous, so this method will return before it is complete. To wait for the flush to complete, use LDClient.FlushAndWait instead (or, if you are done with the SDK, LDClient.Close).

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

func (*LDClient) FlushAndWait

func (client *LDClient) FlushAndWait(timeout time.Duration) bool

FlushAndWait tells the client to deliver any pending analytics events synchronously now.

Unlike LDClient.Flush, this method waits for event delivery to finish. The timeout parameter, if greater than zero, specifies the maximum amount of time to wait. If the timeout elapses before delivery is finished, the method returns early and returns false; in this case, the SDK may still continue trying to deliver the events in the background.

If the timeout parameter is zero or negative, the method waits as long as necessary to deliver the events. However, the SDK does not retry event delivery indefinitely; currently, any network error or server error will cause the SDK to wait one second and retry one time, after which the events will be discarded so that the SDK will not keep consuming more memory for events indefinitely.

The method returns true if event delivery either succeeded, or definitively failed, before the timeout elapsed. It returns false if the timeout elapsed.

This method is also implicitly called if you call LDClient.Close. The difference is that FlushAndWait does not shut down the SDK client.

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 interfaces.BigSegmentStoreStatusProvider 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 interfaces.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 interfaces.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 interfaces.FlagTracker 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 LDClient.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 LDClient.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 LDClient.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 Offline field to true in Config, 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 LDClient.Initialized or LDClient.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 methods such as ldvalue.Value.GetType and ldvalue.Value.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 LDClient.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 LDClient.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 types that are part of the public API, but not needed for basic use of the SDK.
Package interfaces contains types that are part of the public API, but not needed for basic use of the SDK.
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.
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.
sharedtest/mocks
Package mocks contains mocks/spies used within SDK unit tests.
Package mocks contains mocks/spies used within SDK unit tests.
Package ldcomponents provides the standard implementations and configuration options of LaunchDarkly components.
Package ldcomponents provides the standard implementations and configuration options of 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 subsystems contains interfaces for implementation of custom LaunchDarkly components.
Package subsystems contains interfaces for implementation of custom 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.
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 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