ldclient

package module
v4.0.0-...-2a44fb3 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2020 License: Apache-2.0 Imports: 31 Imported by: 24

README

LaunchDarkly Server-side SDK for Go

Circle CI

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.8 through 1.14.

Getting started

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

HTTPS proxy

Go's standard HTTP library provides built-in support for the use of an HTTPS proxy. If the HTTPS_PROXY 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 Redis, Consul, or DynamoDB. These adapters are implemented in the subpackages redis, ldconsul, and lddynamodb; to use them, call the New...FeatureStore function provided by the subpackage, and put the returned object in the FeatureStore field of your client configuration. See the subpackages and the SDK reference guide for more information.

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.

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 that most applications will use. The most commonly used other packages are "ldlog" (the SDK's logging abstraction) and database integrations such as "redis" and "lddynamodb".

Index

Constants

View Source
const (
	FeatureRequestEventKind = "feature"
	FeatureDebugEventKind   = "debug"
	CustomEventKind         = "custom"
	IdentifyEventKind       = "identify"
	IndexEventKind          = "index"
	SummaryEventKind        = "summary"
)

Event types

View Source
const (
	LatestFlagsPath    = "/sdk/latest-flags"
	LatestSegmentsPath = "/sdk/latest-segments"
	LatestAllPath      = "/sdk/latest-all"
)

SDK endpoints

View Source
const MinimumPollInterval = 30 * time.Second

MinimumPollInterval describes the minimum value for Config.PollInterval. If you specify a smaller interval, the minimum will be used instead.

View Source
const Version = "4.17.3"

Version is the client version.

Variables

View Source
var (
	ErrInitializationTimeout = errors.New("timeout encountered waiting for LaunchDarkly client initialization")
	ErrInitializationFailed  = errors.New("LaunchDarkly client initialization failed")
	ErrClientNotInitialized  = errors.New("feature flag evaluation called before LaunchDarkly client initialization completed")
)

Initialization errors

View Source
var DefaultConfig = Config{
	BaseUri:                     "https://app.launchdarkly.com",
	StreamUri:                   "https://stream.launchdarkly.com",
	EventsUri:                   "https://events.launchdarkly.com",
	Capacity:                    10000,
	FlushInterval:               5 * time.Second,
	PollInterval:                MinimumPollInterval,
	Timeout:                     3000 * time.Millisecond,
	Stream:                      true,
	StreamInitialReconnectDelay: defaultStreamRetryDelay,
	FeatureStore:                nil,
	UseLdd:                      false,
	SendEvents:                  true,
	Offline:                     false,
	UserKeysCapacity:            1000,
	UserKeysFlushInterval:       5 * time.Minute,
	UserAgent:                   "",
	Logger:                      defaultLogger,
	DiagnosticRecordingInterval: 15 * time.Minute,
}

DefaultConfig provides the default configuration options for the LaunchDarkly client. The easiest way to create a custom configuration is to start with the default config, and set the custom options from there. For example:

var config = DefaultConfig
config.Capacity = 2000

OpsList is the list of available operators

Deprecated: this variable is for internal use and will be removed in a future version.

View Source
var VersionedDataKinds = [...]VersionedDataKind{
	Features,
	Segments,
}

VersionedDataKinds is a list of supported VersionedDataKind's. Among other things, this list might be used by feature stores to know what data (namespaces) to expect.

Functions

func MakeAllVersionedDataMap deprecated

func MakeAllVersionedDataMap(
	features map[string]*FeatureFlag,
	segments map[string]*Segment) map[VersionedDataKind]map[string]VersionedData

MakeAllVersionedDataMap returns a map of version objects grouped by namespace that can be used to initialize a feature store

Deprecated: this functioin is for internal use and will be removed in a future version.

func ParseFloat64 deprecated

func ParseFloat64(input interface{}) *float64

ParseFloat64 parses a numeric value as float64 from a string or another numeric type. Returns nil pointer if input is nil or unparsable.

Deprecated: this function is for internal use and will be removed in a future version.

func ParseTime deprecated

func ParseTime(input interface{}) *time.Time

ParseTime converts any of the following into a pointer to a time.Time value:

RFC3339/ISO8601 timestamp (example: 2016-04-16T17:09:12.759-07:00)
Unix epoch milliseconds as string
Unix milliseconds as number

Passing in a time.Time value will return a pointer to the input value. Unparsable inputs will return nil More info on RFC3339: http://stackoverflow.com/questions/522251/whats-the-difference-between-iso-8601-and-rfc-3339-date-formats

Deprecated: this function is for internal use and will be removed in a future version.

func ToJsonRawMessage deprecated

func ToJsonRawMessage(input interface{}) (json.RawMessage, error)

ToJsonRawMessage converts input to a *json.RawMessage if possible.

Deprecated: this function is for internal use and will be removed in a future version.

Types

type BaseEvent

type BaseEvent struct {
	CreationDate uint64
	User         User
}

BaseEvent provides properties common to all events.

type Clause deprecated

type Clause struct {
	Attribute string        `json:"attribute" bson:"attribute"`
	Op        Operator      `json:"op" bson:"op"`
	Values    []interface{} `json:"values" bson:"values"` // An array, interpreted as an OR of values
	Negate    bool          `json:"negate" bson:"negate"`
}

Clause describes an individual cluuse within a targeting rule.

Deprecated: this type is for internal use and will be moved to another package in a future version.

type ClientSideAvailability

type ClientSideAvailability struct {
	// UsingMobileKey indicates that this flag is available to clients using the mobile key for authorization
	// (includes most desktop and mobile clients).
	UsingMobileKey bool `json:"usingMobileKey" bson:"usingMobileKey"`
	// UsingEnvironmentID indicates that this flag is available to clients using the environment ID to identify an
	// environment (includes client-side JavaScript clients).
	UsingEnvironmentID bool `json:"usingEnvironmentId" bson:"usingEnvironmentId"`
}

ClientSideAvailability describes what types of SDKs can use this flag.

This information may not always be provided by LaunchDarkly services and/or Relay Proxy instances, and it may not be present if a flag is retrieved from a database that was populated by an older SDK. If this struct does not exist, we will fall back to using the ClientSide field of FeatureFlag.

type Config

type Config struct {
	// The base URI of the main LaunchDarkly service. This should not normally be changed except for testing.
	BaseUri string
	// The base URI of the LaunchDarkly streaming service. This should not normally be changed except for testing.
	StreamUri string
	// The base URI of the LaunchDarkly service that accepts analytics events. This should not normally be
	// changed except for testing.
	EventsUri string
	// The full URI for posting analytics events. This is different from EventsUri in that the client will not
	// add the default URI path to it. It should not normally be changed except for testing, and if set, it
	// causes EventsUri to be ignored.
	EventsEndpointUri string
	// The capacity of the events buffer. The client buffers up to this many events in memory before flushing.
	// If the capacity is exceeded before the buffer is flushed, events will be discarded.
	Capacity int
	// The time between flushes of the event buffer. Decreasing the flush interval means that the event buffer
	// is less likely to reach capacity.
	FlushInterval time.Duration
	// Enables event sampling if non-zero. When set to the default of zero, all events are sent to Launchdarkly.
	// If greater than zero, there is a 1 in SamplingInterval chance that events will be sent (for example, a
	// value of 20 means on average 5% of events will be sent).
	//
	// Deprecated: This feature will be removed in a future version of the SDK.
	SamplingInterval int32
	// The polling interval (when streaming is disabled). Values less than the default of MinimumPollInterval
	// will be set to the default.
	PollInterval time.Duration
	// An object that can be used to produce log output. Setting this property is equivalent to passing
	// the same object to config.Loggers.SetBaseLogger().
	//
	// Deprecated: This property may be removed in the future. Use Loggers.SetBaseLogger() instead.
	Logger Logger
	// Configures the SDK's logging behavior. You may call its SetBaseLogger() method to specify the
	// output destination (the default is standard error), and SetMinLevel() to specify the minimum level
	// of messages to be logged (the default is ldlog.Info).
	Loggers ldlog.Loggers
	// The connection timeout to use when making polling requests to LaunchDarkly.
	Timeout time.Duration
	// Sets the implementation of FeatureStore for holding feature flags and related data received from
	// LaunchDarkly.
	//
	// Except for testing purposes, you should not set this property directly but instead use
	// FeatureStoreFactory, which ensures that the FeatureStore component will use the same logging
	// configuration as the rest of the SDK.
	FeatureStore FeatureStore
	// Sets the implementation of FeatureStore for holding feature flags and related data received from
	// LaunchDarkly. See NewInMemoryFeatureStoreFactory (the default) and the redis, ldconsul, and lddynamodb packages.
	FeatureStoreFactory FeatureStoreFactory
	// Sets whether streaming mode should be enabled. By default, streaming is enabled. It should only be
	// disabled on the advice of LaunchDarkly support.
	Stream bool
	// Sets the initial reconnect delay for the streaming connection.
	//
	// The streaming service uses a backoff algorithm (with jitter) every time the connection needs
	// to be reestablished. The delay for the first reconnection will start near this value, and then
	// increase exponentially for any subsequent connection failures (up to a maximum of 30 seconds).
	//
	// This value is ignored if streaming is disabled. If it is zero, the default of 1 second is used.
	StreamInitialReconnectDelay time.Duration
	// Sets whether this client should use the LaunchDarkly relay in daemon mode. In this mode, the client does
	// not subscribe to the streaming or polling API, but reads data only from the feature store. See:
	// https://docs.launchdarkly.com/docs/the-relay-proxy
	UseLdd bool
	// Sets whether to send analytics events back to LaunchDarkly. By default, the client will send events. This
	// differs from Offline in that it only affects sending events, not streaming or polling for events from the
	// server.
	SendEvents bool
	// 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.
	Offline bool
	// Sets whether or not all user attributes (other than the key) should be hidden from LaunchDarkly. If this
	// is true, all user attribute values will be private, not just the attributes specified in PrivateAttributeNames.
	AllAttributesPrivate bool
	// Set to true if you need to see the full user details in every analytics event.
	InlineUsersInEvents bool
	// Marks a set of user attribute names private. Any users sent to LaunchDarkly with this configuration
	// active will have attributes with these names removed.
	PrivateAttributeNames []string
	// Sets whether the client should log a warning message whenever a flag cannot be evaluated due to an error
	// (e.g. there is no flag with that key, or the user properties are invalid). By default, these messages are
	// not logged, although you can detect such errors programmatically using the VariationDetail methods.
	LogEvaluationErrors bool
	// Sets whether log messages for errors related to a specific user can include the user key. By default, they
	// will not, since the user key might be considered privileged information.
	LogUserKeyInErrors bool
	// Deprecated: Please use UpdateProcessorFactory.
	UpdateProcessor UpdateProcessor
	// Factory to create an object that is responsible for receiving feature flag updates from LaunchDarkly.
	// If nil, a default implementation will be used depending on the rest of the configuration
	// (streaming, polling, etc.); a custom implementation can be substituted for testing.
	UpdateProcessorFactory UpdateProcessorFactory
	// An object that is responsible for recording or sending analytics events. If nil, a
	// default implementation will be used; a custom implementation can be substituted for testing.
	EventProcessor EventProcessor
	// The number of user keys that the event processor can remember at any one time, so that
	// duplicate user details will not be sent in analytics events.
	UserKeysCapacity int
	// The interval at which the event processor will reset its set of known user keys.
	UserKeysFlushInterval time.Duration
	// The User-Agent header to send with HTTP requests. This defaults to a value that identifies the version
	// of the Go SDK for LaunchDarkly usage metrics.
	UserAgent string
	// 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
	// The interval at which periodic diagnostic events will be sent, if DiagnosticOptOut is false.
	//
	// The default is every 15 minutes and the minimum is every minute.
	DiagnosticRecordingInterval time.Duration
	// For use by wrapper libraries to set an identifying name for the wrapper being used.
	//
	// This will be sent in request headers during requests to the LaunchDarkly servers to allow recording
	// metrics on the usage of these wrapper libraries.
	WrapperName string
	// For use by wrapper libraries to set the version to be included alongside a WrapperName.
	//
	// If WrapperName is unset, this field will be ignored.
	WrapperVersion string
	// If not nil, this function will be called to create an HTTP client instead of using the default
	// client. You may use this to specify custom HTTP properties such as a proxy URL or CA certificates.
	// The SDK may modify the client properties after that point (for instance, to add caching),
	// but will not replace the underlying Transport, and will not modify any timeout properties you set.
	// See NewHTTPClientFactory().
	//
	// Usage:
	//
	//     config := ld.DefaultConfig
	//     config.HTTPClientFactory = ld.NewHTTPClientFactory(ldhttp.ProxyURL(myProxyURL))
	HTTPClientFactory HTTPClientFactory
	// contains filtered or unexported fields
}

Config exposes advanced configuration options for the LaunchDarkly client.

type CustomEvent

type CustomEvent struct {
	BaseEvent
	Key         string
	Data        interface{}
	MetricValue *float64
}

CustomEvent is generated by calling the client's Track method.

func NewCustomEvent deprecated

func NewCustomEvent(key string, user User, data interface{}) CustomEvent

NewCustomEvent constructs a new custom event, but does not send it. Typically, Track should be used to both create the event and send it to LaunchDarkly.

Deprecated: This function will be removed in a later release.

func (CustomEvent) GetBase

func (evt CustomEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type DerivedAttribute deprecated

type DerivedAttribute struct {
	Value       interface{} `json:"value" bson:"value"`
	LastDerived time.Time   `json:"lastDerived" bson:"lastDerived"`
}

DerivedAttribute is an entry in a Derived attribute map and is for internal use by LaunchDarkly only. Derived attributes sent to LaunchDarkly are ignored.

Deprecated: this type is for internal use and will be removed in a future version.

type EvalErrorKind

type EvalErrorKind string

EvalErrorKind defines the possible values of the ErrorKind property of EvaluationReason.

const (
	// EvalErrorClientNotReady indicates that the caller tried to evaluate a flag before the client
	// had successfully initialized.
	EvalErrorClientNotReady EvalErrorKind = "CLIENT_NOT_READY"
	// EvalErrorFlagNotFound indicates that the caller provided a flag key that did not match any
	// known flag.
	EvalErrorFlagNotFound EvalErrorKind = "FLAG_NOT_FOUND"
	// EvalErrorMalformedFlag indicates that there was an internal inconsistency in the flag data,
	// e.g. a rule specified a nonexistent variation.
	EvalErrorMalformedFlag EvalErrorKind = "MALFORMED_FLAG"
	// EvalErrorUserNotSpecified indicates that the caller passed a user without a key for the user
	// parameter.
	EvalErrorUserNotSpecified EvalErrorKind = "USER_NOT_SPECIFIED"
	// EvalErrorWrongType indicates that the result value was not of the requested type, e.g. you
	// called BoolVariationDetail but the value was an integer.
	EvalErrorWrongType EvalErrorKind = "WRONG_TYPE"
	// EvalErrorException indicates that an unexpected error stopped flag evaluation; check the
	// log for details.
	EvalErrorException EvalErrorKind = "EXCEPTION"
)

type EvalReasonKind

type EvalReasonKind string

EvalReasonKind defines the possible values of the Kind property of EvaluationReason.

const (
	// EvalReasonOff indicates that the flag was off and therefore returned its configured off value.
	EvalReasonOff EvalReasonKind = "OFF"
	// EvalReasonTargetMatch indicates that the user key was specifically targeted for this flag.
	EvalReasonTargetMatch EvalReasonKind = "TARGET_MATCH"
	// EvalReasonRuleMatch indicates that the user matched one of the flag's rules.
	EvalReasonRuleMatch EvalReasonKind = "RULE_MATCH"
	// EvalReasonPrerequisiteFailed indicates that the flag was considered off because it had at
	// least one prerequisite flag that either was off or did not return the desired variation.
	EvalReasonPrerequisiteFailed EvalReasonKind = "PREREQUISITE_FAILED"
	// EvalReasonFallthrough indicates that the flag was on but the user did not match any targets
	// or rules.
	EvalReasonFallthrough EvalReasonKind = "FALLTHROUGH"
	// EvalReasonError indicates that the flag could not be evaluated, e.g. because it does not
	// exist or due to an unexpected error. In this case the result value will be the default value
	// that the caller passed to the client.
	EvalReasonError EvalReasonKind = "ERROR"
)

type EvalResult deprecated

type EvalResult struct {
	Value                     interface{}
	Variation                 *int
	Explanation               *Explanation
	PrerequisiteRequestEvents []FeatureRequestEvent //to be sent to LD
}

EvalResult describes the value and variation index that are the result of flag evaluation. It also includes a list of any prerequisite flags that were evaluated to generate the evaluation.

Deprecated: this type is for internal use and will be removed in a future version.

type EvaluationDetail

type EvaluationDetail struct {
	// Value is the result of the flag evaluation. This will be either one of the flag's variations or
	// the default value that was passed to the Variation method.
	//
	// Deprecated: Use JSONValue instead. The Value property will be removed in a future version.
	Value interface{}
	// JSONValue is the result of the flag evaluation, represented with the ldvalue.Value type.
	// This is always the same value you would get by calling LDClient.JSONVariation(). You can
	// convert it to a bool, int, string, etc. using methods of ldvalue.Value.
	//
	// This property is preferred over EvaluationDetail.Value, because the interface{} type of Value
	// can expose a mutable data structure (slice or map) and accidentally modifying such a structure
	// could affect SDK behavior.
	JSONValue ldvalue.Value
	// VariationIndex is the index of the returned value within the flag's list of variations, e.g.
	// 0 for the first variation - or nil if the default value was returned.
	VariationIndex *int
	// Reason is an EvaluationReason object describing the main factor that influenced the flag
	// evaluation value.
	Reason EvaluationReason
}

EvaluationDetail is an object returned by LDClient.VariationDetail, combining the result of a flag evaluation with an explanation of how it was calculated.

func NewEvaluationDetail

func NewEvaluationDetail(jsonValue ldvalue.Value, variationIndex *int, reason EvaluationReason) EvaluationDetail

NewEvaluationDetail creates an EvaluationDetail, specifying all fields. The deprecated Value property is set to the same value that is wrapped by jsonValue.

func NewEvaluationError

func NewEvaluationError(jsonValue ldvalue.Value, errorKind EvalErrorKind) EvaluationDetail

NewEvaluationError creates an EvaluationDetail describing an error. The deprecated Value property is set to the same value that is wrapped by jsonValue.

func (EvaluationDetail) IsDefaultValue

func (d EvaluationDetail) IsDefaultValue() bool

IsDefaultValue returns true if the result of the evaluation was the default value.

type EvaluationReason

type EvaluationReason interface {
	fmt.Stringer

	// GetKind describes the general category of the reason.
	GetKind() EvalReasonKind

	// GetRuleIndex provides the index of the rule that was matched (0 being the first), if
	// the Kind is EvalReasonRuleMatch. Otherwise it returns -1.
	GetRuleIndex() int

	// GetRuleID provides the unique identifier of the rule that was matched, if the Kind is
	// EvalReasonRuleMatch. Otherwise it returns an empty string. Unlike the rule index, this
	// identifier will not change if other rules are added or deleted.
	GetRuleID() string

	// GetPrerequisiteKey provides the flag key of the prerequisite that failed, if the Kind
	// is EvalReasonPrerequisiteFailed. Otherwise it returns an empty string.
	GetPrerequisiteKey() string

	// GetErrorKind describes the general category of the error, if the Kind is EvalReasonError.
	// Otherwise it returns an empty string.
	GetErrorKind() EvalErrorKind
}

EvaluationReason describes the reason that a flag evaluation producted a particular value. Specific kinds of reasons have their own types that implement this interface.

Note: In a future version, EvaluationReason will be a struct, and the currently existing structs implementing this interface (EvaluationReasonOff, etc.) will be removed. For compatibility, avoid referencing those types and use only the EvaluationReason methods.

type EvaluationReasonContainer

type EvaluationReasonContainer struct {
	Reason EvaluationReason
}

EvaluationReasonContainer is used internally in cases where LaunchDarkly needs to unnmarshal an EvaluationReason value from JSON. This is necessary because UnmarshalJSON cannot be implemented for interfaces.

func (EvaluationReasonContainer) MarshalJSON

func (c EvaluationReasonContainer) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON serialization for EvaluationReasonContainer.

func (*EvaluationReasonContainer) UnmarshalJSON

func (c *EvaluationReasonContainer) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON deserialization for EvaluationReasonContainer.

type EvaluationReasonError deprecated

type EvaluationReasonError struct {

	// ErrorKind describes the type of error.
	ErrorKind EvalErrorKind `json:"errorKind"`
	// contains filtered or unexported fields
}

EvaluationReasonError means that the flag could not be evaluated, e.g. because it does not exist or due to an unexpected error.

Deprecated: This type will be removed in a future version. Use the GetKind() method on EvaluationReason instead to test for EvalReasonError, and use GetErrorKind() instead of accessing the ErrorKind field directly.

func (EvaluationReasonError) GetErrorKind

func (r EvaluationReasonError) GetErrorKind() EvalErrorKind

GetErrorKind describes the general category of the error.

func (EvaluationReasonError) GetKind

func (r EvaluationReasonError) GetKind() EvalReasonKind

func (EvaluationReasonError) GetPrerequisiteKey

func (r EvaluationReasonError) GetPrerequisiteKey() string

GetPrerequisiteKey for this type always returns an empty string.

func (EvaluationReasonError) GetRuleID

func (r EvaluationReasonError) GetRuleID() string

GetRuleID for this type always returns an empty string.

func (EvaluationReasonError) GetRuleIndex

func (r EvaluationReasonError) GetRuleIndex() int

GetRuleIndex for this type always returns -1.

func (EvaluationReasonError) String

func (r EvaluationReasonError) String() string

type EvaluationReasonFallthrough deprecated

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

EvaluationReasonFallthrough means that the flag was on but the user did not match any targets or rules.

Deprecated: This type will be removed in a future version. Use the GetKind() method on EvaluationReason instead to test for EvalReasonFallthrough.

func (EvaluationReasonFallthrough) GetErrorKind

func (r EvaluationReasonFallthrough) GetErrorKind() EvalErrorKind

GetErrorKind for this type always returns an empty string.

func (EvaluationReasonFallthrough) GetKind

func (r EvaluationReasonFallthrough) GetKind() EvalReasonKind

func (EvaluationReasonFallthrough) GetPrerequisiteKey

func (r EvaluationReasonFallthrough) GetPrerequisiteKey() string

GetPrerequisiteKey for this type always returns an empty string.

func (EvaluationReasonFallthrough) GetRuleID

func (r EvaluationReasonFallthrough) GetRuleID() string

GetRuleID for this type always returns an empty string.

func (EvaluationReasonFallthrough) GetRuleIndex

func (r EvaluationReasonFallthrough) GetRuleIndex() int

GetRuleIndex for this type always returns -1.

func (EvaluationReasonFallthrough) String

type EvaluationReasonOff deprecated

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

EvaluationReasonOff means that the flag was off and therefore returned its configured off value.

Deprecated: This type will be removed in a future version. Use the GetKind() method on EvaluationReason instead to test for EvalReasonOff.

func (EvaluationReasonOff) GetErrorKind

func (r EvaluationReasonOff) GetErrorKind() EvalErrorKind

GetErrorKind for this type always returns an empty string.

func (EvaluationReasonOff) GetKind

func (r EvaluationReasonOff) GetKind() EvalReasonKind

func (EvaluationReasonOff) GetPrerequisiteKey

func (r EvaluationReasonOff) GetPrerequisiteKey() string

GetPrerequisiteKey for this type always returns an empty string.

func (EvaluationReasonOff) GetRuleID

func (r EvaluationReasonOff) GetRuleID() string

GetRuleID for this type always returns an empty string.

func (EvaluationReasonOff) GetRuleIndex

func (r EvaluationReasonOff) GetRuleIndex() int

GetRuleIndex for this type always returns -1.

func (EvaluationReasonOff) String

func (r EvaluationReasonOff) String() string

type EvaluationReasonPrerequisiteFailed deprecated

type EvaluationReasonPrerequisiteFailed struct {

	// PrerequisiteKey is the flag key of the prerequisite that failed.
	PrerequisiteKey string `json:"prerequisiteKey"`
	// contains filtered or unexported fields
}

EvaluationReasonPrerequisiteFailed means that the flag was considered off because it had at least one prerequisite flag that either was off or did not return the desired variation.

Deprecated: This type will be removed in a future version. Use the GetKind() method on EvaluationReason instead to test for EvalReasonPrerequisiteFailed, and use GetPrerequisiteKey() instead of accessing the PrerequisiteKey field directly.

func (EvaluationReasonPrerequisiteFailed) GetErrorKind

GetErrorKind for this type always returns an empty string.

func (EvaluationReasonPrerequisiteFailed) GetKind

func (r EvaluationReasonPrerequisiteFailed) GetKind() EvalReasonKind

func (EvaluationReasonPrerequisiteFailed) GetPrerequisiteKey

func (r EvaluationReasonPrerequisiteFailed) GetPrerequisiteKey() string

GetPrerequisiteKey provides the flag key of the prerequisite that failed.

func (EvaluationReasonPrerequisiteFailed) GetRuleID

GetRuleID for this type always returns an empty string.

func (EvaluationReasonPrerequisiteFailed) GetRuleIndex

func (r EvaluationReasonPrerequisiteFailed) GetRuleIndex() int

GetRuleIndex for this type always returns -1.

func (EvaluationReasonPrerequisiteFailed) String

type EvaluationReasonRuleMatch deprecated

type EvaluationReasonRuleMatch struct {

	// RuleIndex is the index of the rule that was matched (0 being the first).
	RuleIndex int `json:"ruleIndex"`
	// RuleID is the unique identifier of the rule that was matched.
	RuleID string `json:"ruleId"`
	// contains filtered or unexported fields
}

EvaluationReasonRuleMatch means that the user matched one of the flag's rules.

Deprecated: This type will be removed in a future version. Use the GetKind() method on EvaluationReason instead to test for EvalReasonRuleMatch, and use GetRuleIndex() or GetRuleID() instead of accessing the RuleIndex and RuleID fields directly.

func (EvaluationReasonRuleMatch) GetErrorKind

func (r EvaluationReasonRuleMatch) GetErrorKind() EvalErrorKind

GetErrorKind for this type always returns an empty string.

func (EvaluationReasonRuleMatch) GetKind

func (r EvaluationReasonRuleMatch) GetKind() EvalReasonKind

func (EvaluationReasonRuleMatch) GetPrerequisiteKey

func (r EvaluationReasonRuleMatch) GetPrerequisiteKey() string

GetPrerequisiteKey for this type always returns an empty string.

func (EvaluationReasonRuleMatch) GetRuleID

func (r EvaluationReasonRuleMatch) GetRuleID() string

GetRuleID provides the unique identifier of the rule that was matched.

func (EvaluationReasonRuleMatch) GetRuleIndex

func (r EvaluationReasonRuleMatch) GetRuleIndex() int

GetRuleIndex provides the index of the rule that was matched (0 being the first).

func (EvaluationReasonRuleMatch) String

func (r EvaluationReasonRuleMatch) String() string

type EvaluationReasonTargetMatch deprecated

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

EvaluationReasonTargetMatch means that the user key was specifically targeted for this flag.

Deprecated: This type will be removed in a future version. Use the GetKind() method on EvaluationReason instead to test for EvalReasonTargetMatch.

func (EvaluationReasonTargetMatch) GetErrorKind

func (r EvaluationReasonTargetMatch) GetErrorKind() EvalErrorKind

GetErrorKind for this type always returns an empty string.

func (EvaluationReasonTargetMatch) GetKind

func (r EvaluationReasonTargetMatch) GetKind() EvalReasonKind

func (EvaluationReasonTargetMatch) GetPrerequisiteKey

func (r EvaluationReasonTargetMatch) GetPrerequisiteKey() string

GetPrerequisiteKey for this type always returns an empty string.

func (EvaluationReasonTargetMatch) GetRuleID

func (r EvaluationReasonTargetMatch) GetRuleID() string

GetRuleID for this type always returns an empty string.

func (EvaluationReasonTargetMatch) GetRuleIndex

func (r EvaluationReasonTargetMatch) GetRuleIndex() int

GetRuleIndex for this type always returns -1.

func (EvaluationReasonTargetMatch) String

type Event

type Event interface {
	GetBase() BaseEvent
}

An Event represents an analytics event generated by the client, which will be passed to the EventProcessor. The event data that the EventProcessor actually sends to LaunchDarkly may be slightly different.

type EventProcessor

type EventProcessor interface {
	// SendEvent records an event asynchronously.
	SendEvent(Event)
	// Flush specifies that any buffered events should be sent as soon as possible, rather than waiting
	// for the next flush interval. This method is asynchronous, so events still may not be sent
	// until a later time.
	Flush()
	// Close shuts down all event processor activity, after first ensuring that all events have been
	// delivered. Subsequent calls to SendEvent() or Flush() will be ignored.
	Close() error
}

EventProcessor defines the interface for dispatching analytics events.

func NewDefaultEventProcessor

func NewDefaultEventProcessor(sdkKey string, config Config, client *http.Client) EventProcessor

NewDefaultEventProcessor creates an instance of the default implementation of analytics event processing. This is normally only used internally; it is public because the Go SDK code is reused by other LaunchDarkly components.

type Explanation deprecated

type Explanation struct {
	Kind                string `json:"kind" bson:"kind"`
	*Target             `json:"target,omitempty"`
	*Rule               `json:"rule,omitempty"`
	*Prerequisite       `json:"prerequisite,omitempty"`
	*VariationOrRollout `json:"fallthrough,omitempty"`
}

Explanation is an obsolete type that is used by the deprecated EvaluateExplain method.

Deprecated: Use the VariationDetail methods and the EvaluationDetail type instead.

type Feature

type Feature struct {
	Name         *string      `json:"name"`
	Key          *string      `json:"key"`
	Kind         *string      `json:"kind"`
	Salt         *string      `json:"salt"`
	On           *bool        `json:"on"`
	Variations   *[]Variation `json:"variations"`
	CommitDate   *time.Time   `json:"commitDate"`
	CreationDate *time.Time   `json:"creationDate"`
	Version      int          `json:"version,omitempty"`
	Deleted      bool         `json:"deleted,omitempty"`
}

Feature describes a Legacy (v1) feature

func (Feature) Evaluate

func (f Feature) Evaluate(user User) (value interface{}, rulesPassed bool)

Evaluate returns the value of a feature for a specified user

func (Feature) EvaluateExplain

func (f Feature) EvaluateExplain(user User) (value interface{}, targetMatch *TargetRule, rulesPassed bool)

EvaluateExplain returns the value of a feature for a specified user with an explanation of which rule was applied

type FeatureFlag deprecated

type FeatureFlag struct {
	Key                    string                  `json:"key" bson:"key"`
	Version                int                     `json:"version" bson:"version"`
	On                     bool                    `json:"on" bson:"on"`
	TrackEvents            bool                    `json:"trackEvents" bson:"trackEvents"`
	TrackEventsFallthrough bool                    `json:"trackEventsFallthrough" bson:"trackEventsFallthrough"`
	Deleted                bool                    `json:"deleted" bson:"deleted"`
	Prerequisites          []Prerequisite          `json:"prerequisites" bson:"prerequisites"`
	Salt                   string                  `json:"salt" bson:"salt"`
	Sel                    string                  `json:"sel" bson:"sel"`
	Targets                []Target                `json:"targets" bson:"targets"`
	Rules                  []Rule                  `json:"rules" bson:"rules"`
	Fallthrough            VariationOrRollout      `json:"fallthrough" bson:"fallthrough"`
	OffVariation           *int                    `json:"offVariation" bson:"offVariation"`
	Variations             []interface{}           `json:"variations" bson:"variations"`
	DebugEventsUntilDate   *uint64                 `json:"debugEventsUntilDate" bson:"debugEventsUntilDate"`
	ClientSide             bool                    `json:"clientSide" bson:"-"`
	ClientSideAvailability *ClientSideAvailability `json:"clientSideAvailability,omitempty" bson:"clientSideAvailability,omitempty"`
}

FeatureFlag describes an individual feature flag.

Deprecated: this type is for internal use and will be moved to another package in a future version.

func (*FeatureFlag) Clone

func (f *FeatureFlag) Clone() VersionedData

Clone returns a copy of a flag

func (FeatureFlag) Evaluate deprecated

func (f FeatureFlag) Evaluate(user User, store FeatureStore) (interface{}, *int, []FeatureRequestEvent)

Evaluate returns the variation selected for a user. It also contains a list of events generated during evaluation.

Deprecated: this method is for internal use and will be removed in a future version.

func (FeatureFlag) EvaluateDetail deprecated

func (f FeatureFlag) EvaluateDetail(user User, store FeatureStore, sendReasonsInEvents bool) (EvaluationDetail, []FeatureRequestEvent)

EvaluateDetail attempts to evaluate the feature flag for the given user and returns its value, the reason for the value, and any events generated by prerequisite flags.

Deprecated: this method is for internal use and will be moved to another package in a future version.

func (FeatureFlag) EvaluateExplain deprecated

func (f FeatureFlag) EvaluateExplain(user User, store FeatureStore) (*EvalResult, error)

EvaluateExplain returns the variation selected for a user along with a detailed explanation of which rule resulted in the selected variation.

Deprecated: this method is for internal use and will be removed in a future version.

func (*FeatureFlag) GetKey

func (f *FeatureFlag) GetKey() string

GetKey returns the string key for the feature flag

func (*FeatureFlag) GetVersion

func (f *FeatureFlag) GetVersion() int

GetVersion returns the version of a flag

func (*FeatureFlag) IsDeleted

func (f *FeatureFlag) IsDeleted() bool

IsDeleted returns whether a flag has been deleted

type FeatureFlagVersionedDataKind deprecated

type FeatureFlagVersionedDataKind struct{}

FeatureFlagVersionedDataKind implements VersionedDataKind and provides methods to build storage engine for flags.

Deprecated: this type is for internal use and will be removed in a future version.

Features is convenience variable to access an instance of FeatureFlagVersionedDataKind.

Deprecated: this variable is for internal use and will be removed in a future version.

func (FeatureFlagVersionedDataKind) GetDefaultItem

func (fk FeatureFlagVersionedDataKind) GetDefaultItem() interface{}

GetDefaultItem returns a default feature flag representation

func (FeatureFlagVersionedDataKind) GetNamespace

func (fk FeatureFlagVersionedDataKind) GetNamespace() string

GetNamespace returns the a unique namespace identifier for feature flag objects

func (FeatureFlagVersionedDataKind) MakeDeletedItem

func (fk FeatureFlagVersionedDataKind) MakeDeletedItem(key string, version int) VersionedData

MakeDeletedItem returns representation of a deleted flag

func (FeatureFlagVersionedDataKind) String

String returns the namespace

type FeatureFlagsState

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

FeatureFlagsState is a snapshot of the state of all feature flags with regard to a specific user, generated by calling LDClient.AllFlagsState(). Serializing this object to JSON using json.Marshal will produce the appropriate data structure for bootstrapping the LaunchDarkly JavaScript client.

func (FeatureFlagsState) GetFlagReason

func (s FeatureFlagsState) GetFlagReason(key string) EvaluationReason

GetFlagReason returns the evaluation reason for an individual feature flag at the time the state was recorded. The return value will be nil if reasons were not recorded, or if there was no such flag.

func (FeatureFlagsState) GetFlagValue

func (s FeatureFlagsState) GetFlagValue(key string) interface{}

GetFlagValue returns the value of an individual feature flag at the time the state was recorded. The return value will be nil if the flag returned the default value, or if there was no such flag.

func (FeatureFlagsState) IsValid

func (s FeatureFlagsState) IsValid() bool

IsValid returns true if this object contains a valid snapshot of feature flag state, or false if the state could not be computed (for instance, because the client was offline or there was no user).

func (FeatureFlagsState) MarshalJSON

func (s FeatureFlagsState) MarshalJSON() ([]byte, error)

MarshalJSON implements a custom JSON serialization for FeatureFlagsState, to produce the correct data structure for "bootstrapping" the LaunchDarkly JavaScript client.

func (FeatureFlagsState) ToValuesMap

func (s FeatureFlagsState) ToValuesMap() map[string]interface{}

ToValuesMap returns a map of flag keys to flag values. If a flag would have evaluated to the default value, its value will be nil.

Do not use this method if you are passing data to the front end to "bootstrap" the JavaScript client. Instead, convert the state object to JSON using json.Marshal.

type FeatureRequestEvent

type FeatureRequestEvent struct {
	BaseEvent
	Key       string
	Variation *int
	Value     interface{}
	Default   interface{}
	Version   *int
	PrereqOf  *string
	Reason    EvaluationReasonContainer
	// Note, we need to use EvaluationReasonContainer here because FeatureRequestEvent can be
	// deserialized by ld-relay.
	TrackEvents          bool
	Debug                bool
	DebugEventsUntilDate *uint64
}

FeatureRequestEvent is generated by evaluating a feature flag or one of a flag's prerequisites.

func NewFeatureRequestEvent deprecated

func NewFeatureRequestEvent(key string, flag *FeatureFlag, user User, variation *int, value, defaultVal interface{}, prereqOf *string) FeatureRequestEvent

NewFeatureRequestEvent creates a feature request event. Normally, you don't need to call this; the event is created and queued automatically during feature flag evaluation.

Deprecated: This function will be removed in a later release.

func (FeatureRequestEvent) GetBase

func (evt FeatureRequestEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type FeatureStore

type FeatureStore interface {
	// Get attempts to retrieve an item of the specified kind from the data store using its unique key.
	// If no such item exists, it returns nil. If the item exists but has a Deleted property that is true,
	// it returns nil.
	Get(kind VersionedDataKind, key string) (VersionedData, error)
	// All retrieves all items of the specified kind from the data store, returning a map of keys to
	// items. Any items whose Deleted property is true must be omitted. If the store is empty, it
	// returns an empty map.
	All(kind VersionedDataKind) (map[string]VersionedData, error)
	// Init performs an update of the entire data store, replacing any existing data.
	Init(data map[VersionedDataKind]map[string]VersionedData) error
	// Delete removes the specified item from the data store, unless its Version property is greater
	// than or equal to the specified version, in which case nothing happens. Removal should be done
	// by storing an item whose Deleted property is true (use VersionedDataKind.MakeDeleteItem()).
	Delete(kind VersionedDataKind, key string, version int) error
	// Upsert adds or updates the specified item, unless the existing item in the store has a Version
	// property greater than or equal to the new item's Version, in which case nothing happens.
	Upsert(kind VersionedDataKind, item VersionedData) error
	// Initialized returns true if the data store contains a data set, meaning that Init has been
	// called at least once. In a shared data store, it should be able to detect this even if Init
	// was called in a different process, i.e. the test should be based on looking at what is in
	// the data store. Once this has been determined to be true, it can continue to return true
	// without having to check the store again; this method should be as fast as possible since it
	// may be called during feature flag evaluations.
	Initialized() bool
}

FeatureStore is an interface describing a structure that maintains the live collection of features and related objects. Whenever the SDK retrieves feature flag data from LaunchDarkly, via streaming or polling, it puts the data into the FeatureStore; then it queries the store whenever a flag needs to be evaluated. Therefore, implementations must be thread-safe.

The SDK provides a default in-memory implementation (NewInMemoryFeatureStore), as well as database integrations in the "redis", "ldconsul", and "lddynamodb" packages. To use an implementation other than the default, put an instance of it in the FeatureStore property of your client configuration.

If you want to create a custom implementation, it may be helpful to use the FeatureStoreWrapper type in the utils package; this provides commonly desired behaviors such as caching. Custom implementations must be able to handle any objects that implement the VersionedData interface, so if they need to marshal objects, the marshaling must be reflection-based. The VersionedDataKind type provides the necessary metadata to support this.

type FeatureStoreFactory

type FeatureStoreFactory func(config Config) (FeatureStore, error)

FeatureStoreFactory is a factory function that produces a FeatureStore implementation. It receives a copy of the Config so that it can use the same logging configuration as the rest of the SDK; it can assume that config.Loggers has been initialized so it can write to any log level.

func NewInMemoryFeatureStoreFactory

func NewInMemoryFeatureStoreFactory() FeatureStoreFactory

NewInMemoryFeatureStoreFactory returns a factory function to create an in-memory FeatureStore. Setting the FeatureStoreFactory option in Config to this function ensures that it will use the same logging configuration as the other SDK components.

type FlagsStateOption

type FlagsStateOption interface {
	fmt.Stringer
}

FlagsStateOption is the type of optional parameters that can be passed to LDClient.AllFlagsState.

var ClientSideOnly FlagsStateOption = clientSideOnlyFlagsStateOption{}

ClientSideOnly - when passed to LDClient.AllFlagsState() - specifies that only flags marked for use with the client-side SDK should be included in the state object. By default, all flags are included.

var DetailsOnlyForTrackedFlags FlagsStateOption = detailsOnlyForTrackedFlagsOption{}

DetailsOnlyForTrackedFlags - when passed to LDClient.AllFlagsState() - specifies that any flag metadata that is normally only used for event generation - such as flag versions and evaluation reasons - should be omitted for any flag that does not have event tracking or debugging turned on. This reduces the size of the JSON data if you are passing the flag state to the front end.

var WithReasons FlagsStateOption = withReasonsFlagsStateOption{}

WithReasons - when passed to LDClient.AllFlagsState() - specifies that evaluation reasons should be included in the state object. By default, they are not.

type HTTPClientFactory

type HTTPClientFactory func(Config) http.Client

HTTPClientFactory is a function that creates a custom HTTP client.

func NewHTTPClientFactory

func NewHTTPClientFactory(options ...ldhttp.TransportOption) HTTPClientFactory

NewHTTPClientFactory creates an HTTPClientFactory based on the standard SDK configuration as well as any custom ldhttp.TransportOption properties you specify.

Usage:

config := ld.DefaultConfig
config.HTTPClientFactory = ld.NewHTTPClientFactory(ldhttp.CACertFileOption("my-cert.pem"))

type HttpStatusError deprecated

type HttpStatusError struct {
	Message string
	Code    int
}

HttpStatusError describes an http error

Deprecated: this type is for internal use and will be removed in a future version.

func (HttpStatusError) Error

func (e HttpStatusError) Error() string

Error returns a the error message for an http status error

type IdentifyEvent

type IdentifyEvent struct {
	BaseEvent
}

IdentifyEvent is generated by calling the client's Identify method.

func NewIdentifyEvent

func NewIdentifyEvent(user User) IdentifyEvent

NewIdentifyEvent constructs a new identify event, but does not send it. Typically, Identify should be used to both create the event and send it to LaunchDarkly.

func (IdentifyEvent) GetBase

func (evt IdentifyEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type InMemoryFeatureStore

type InMemoryFeatureStore struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

InMemoryFeatureStore is a memory based FeatureStore implementation, backed by a lock-striped map.

func NewInMemoryFeatureStore deprecated

func NewInMemoryFeatureStore(logger Logger) *InMemoryFeatureStore

NewInMemoryFeatureStore creates a new in-memory FeatureStore instance.

Deprecated: Specific implementation types such as InMemoryFeatureStore should not be used and may be removed in the future. Instead, use NewInMemoryFeatureStoreFactory.

func (*InMemoryFeatureStore) All

All returns all the objects of a given kind from the store

func (*InMemoryFeatureStore) Delete

func (store *InMemoryFeatureStore) Delete(kind VersionedDataKind, key string, version int) error

Delete removes an item of a given kind from the store

func (*InMemoryFeatureStore) Get

Get returns an individual object of a given type from the store

func (*InMemoryFeatureStore) GetDiagnosticsComponentTypeName

func (store *InMemoryFeatureStore) GetDiagnosticsComponentTypeName() string

Used internally to describe this component in diagnostic data.

func (*InMemoryFeatureStore) Init

func (store *InMemoryFeatureStore) Init(allData map[VersionedDataKind]map[string]VersionedData) error

Init populates the store with a complete set of versioned data

func (*InMemoryFeatureStore) Initialized

func (store *InMemoryFeatureStore) Initialized() bool

Initialized returns whether the store has been initialized with data

func (*InMemoryFeatureStore) Upsert

func (store *InMemoryFeatureStore) Upsert(kind VersionedDataKind, item VersionedData) error

Upsert inserts or replaces an item in the store unless there it already contains an item with an equal or larger version

type IndexEvent

type IndexEvent struct {
	BaseEvent
}

IndexEvent is generated internally to capture user details from other events.

func (IndexEvent) GetBase

func (evt IndexEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type LDClient

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

LDClient is the LaunchDarkly client. Client instances are thread-safe. Applications should instantiate a single instance for the lifetime of their application.

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. In most cases, you should use this method to instantiate your client. The optional duration parameter allows callers to block until the client has connected to LaunchDarkly and is properly initialized.

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 optional duration parameter allows callers to block until the client has connected to LaunchDarkly and is properly initialized.

func (*LDClient) AllFlags deprecated

func (client *LDClient) AllFlags(user User) map[string]interface{}

AllFlags returns a map from feature flag keys to values for a given user. If the result of the flag's evaluation would result in the default value, `nil` will be returned. This method does not send analytics events back to LaunchDarkly

Deprecated: Use AllFlagsState instead. Current versions of the client-side SDK will not generate analytics events correctly if you pass the result of AllFlags.

func (*LDClient) AllFlagsState

func (client *LDClient) AllFlagsState(user User, options ...FlagsStateOption) FeatureFlagsState

AllFlagsState returns an object that encapsulates the state of all feature flags for a given user, including the flag values and also metadata that can be used on the front end. You may pass any combination of ClientSideOnly, WithReasons, and DetailsOnlyForTrackedFlags as optional parameters to control what data is included.

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

func (*LDClient) BoolVariation

func (client *LDClient) BoolVariation(key string, user User, defaultVal bool) (bool, error)

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

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

func (*LDClient) BoolVariationDetail

func (client *LDClient) BoolVariationDetail(key string, user User, defaultVal bool) (bool, 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.

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) Evaluate deprecated

func (client *LDClient) Evaluate(key string, user User, defaultVal interface{}) (interface{}, *int, error)

Evaluate returns the value of a feature for a specified user.

Deprecated: Use one of the Variation methods (JSONVariation if you do not need a specific type).

func (*LDClient) Float64Variation

func (client *LDClient) Float64Variation(key string, user User, defaultVal float64) (float64, error)

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

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

func (*LDClient) Float64VariationDetail

func (client *LDClient) Float64VariationDetail(key string, user User, defaultVal float64) (float64, 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.

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.

func (*LDClient) Identify

func (client *LDClient) Identify(user User) error

Identify reports details about a a user.

func (*LDClient) Initialized

func (client *LDClient) Initialized() bool

Initialized returns whether the LaunchDarkly client is initialized.

func (*LDClient) IntVariation

func (client *LDClient) IntVariation(key string, user User, defaultVal int) (int, error)

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

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).

func (*LDClient) IntVariationDetail

func (client *LDClient) IntVariationDetail(key string, user User, defaultVal int) (int, 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.

func (*LDClient) IsOffline

func (client *LDClient) IsOffline() bool

IsOffline returns whether the LaunchDarkly client is in offline mode.

func (*LDClient) JSONVariation

func (client *LDClient) JSONVariation(key string, user User, defaultVal ldvalue.Value) (ldvalue.Value, error)

JSONVariation returns the value of a feature flag for the given user, 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, user, 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, user, defaultValAsJSON
resultAsRawJSON := result.AsRaw()

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

func (*LDClient) JSONVariationDetail

func (client *LDClient) JSONVariationDetail(key string, user User, defaultVal ldvalue.Value) (ldvalue.Value, 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.

func (*LDClient) JsonVariation deprecated

func (client *LDClient) JsonVariation(key string, user User, defaultVal json.RawMessage) (json.RawMessage, error)

Obsolete alternative to JSONVariation.

Deprecated: See JSONVariation.

func (*LDClient) JsonVariationDetail deprecated

func (client *LDClient) JsonVariationDetail(key string, user User, defaultVal json.RawMessage) (json.RawMessage, EvaluationDetail, error)

Obsolete alternative to JSONVariationDetail.

Deprecated: See JSONVariationDetail.

func (*LDClient) SecureModeHash

func (client *LDClient) SecureModeHash(user User) string

SecureModeHash generates the secure mode hash value for a user See https://github.com/launchdarkly/js-client#secure-mode

func (*LDClient) StringVariation

func (client *LDClient) StringVariation(key string, user User, defaultVal string) (string, error)

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

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

func (*LDClient) StringVariationDetail

func (client *LDClient) StringVariationDetail(key string, user User, defaultVal string) (string, 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.

func (*LDClient) Track deprecated

func (client *LDClient) Track(eventName string, user User, data interface{}) error

Track reports that a user has performed an event.

The data parameter is a value of any type that will be serialized to JSON using the encoding/json package (http://golang.org/pkg/encoding/json/) and sent with the event. It may be nil if no such value is needed.

Deprecated: Use TrackData, which uses the ldvalue.Value type to more safely represent only allowable JSON types.

func (*LDClient) TrackData

func (client *LDClient) TrackData(eventName string, user User, data ldvalue.Value) error

TrackData reports that a user has performed an event, and associates it with 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.

func (*LDClient) TrackEvent

func (client *LDClient) TrackEvent(eventName string, user User) error

TrackEvent reports that a user has performed an event.

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.

func (*LDClient) TrackMetric

func (client *LDClient) TrackMetric(eventName string, user User, metricValue float64, data ldvalue.Value) error

TrackMetric reports that a user has performed an event, and associates it with 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().

func (*LDClient) TrackWithMetric deprecated

func (client *LDClient) TrackWithMetric(eventName string, user User, data interface{}, metricValue float64) error

TrackWithMetric reports that a user has performed an event, and associates it with 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.

Custom data can also be attached to the event, and is serialized to JSON using the encoding/json package (http://golang.org/pkg/encoding/json/).

Deprecated: Use TrackMetric, which uses the ldvalue.Value type to more safely represent only allowable JSON types.

type Logger

type Logger interface {
	Println(...interface{})
	Printf(string, ...interface{})
}

Logger is a generic logger interface.

type Operator deprecated

type Operator string

Operator describes an operator for a clause.

Deprecated: this type is for internal use and will be moved to another package in a future version.

const (
	OperatorIn                 Operator = "in"
	OperatorEndsWith           Operator = "endsWith"
	OperatorStartsWith         Operator = "startsWith"
	OperatorMatches            Operator = "matches"
	OperatorContains           Operator = "contains"
	OperatorLessThan           Operator = "lessThan"
	OperatorLessThanOrEqual    Operator = "lessThanOrEqual"
	OperatorGreaterThan        Operator = "greaterThan"
	OperatorGreaterThanOrEqual Operator = "greaterThanOrEqual"
	OperatorBefore             Operator = "before"
	OperatorAfter              Operator = "after"
	OperatorSegmentMatch       Operator = "segmentMatch"
	OperatorSemVerEqual        Operator = "semVerEqual"
	OperatorSemVerLessThan     Operator = "semVerLessThan"
	OperatorSemVerGreaterThan  Operator = "semVerGreaterThan"
)

List of available operators

func (Operator) Name

func (op Operator) Name() string

Name returns the string name for an operator

type Prerequisite deprecated

type Prerequisite struct {
	Key       string `json:"key"`
	Variation int    `json:"variation"`
}

Prerequisite describes a requirement that another feature flag return a specific variation.

Deprecated: this type is for internal use and will be moved to another package in a future version.

type Rollout deprecated

type Rollout struct {
	Variations []WeightedVariation `json:"variations" bson:"variations"`
	BucketBy   *string             `json:"bucketBy,omitempty" bson:"bucketBy,omitempty"`
}

Rollout describes how users will be bucketed into variations during a percentage rollout.

Deprecated: this type is for internal use and will be moved to another package in a future version.

type Rule deprecated

type Rule struct {
	ID                 string `json:"id,omitempty" bson:"id,omitempty"`
	VariationOrRollout `bson:",inline"`
	Clauses            []Clause `json:"clauses" bson:"clauses"`
	TrackEvents        bool     `json:"trackEvents" bson:"trackEvents"`
}

Rule expresses a set of AND-ed matching conditions for a user, along with either a fixed variation or a set of rollout percentages.

Deprecated: this type is for internal use and will be moved to another package in a future version.

type Segment deprecated

type Segment struct {
	Key      string        `json:"key" bson:"key"`
	Included []string      `json:"included" bson:"included"`
	Excluded []string      `json:"excluded" bson:"excluded"`
	Salt     string        `json:"salt" bson:"salt"`
	Rules    []SegmentRule `json:"rules" bson:"rules"`
	Version  int           `json:"version" bson:"version"`
	Deleted  bool          `json:"deleted" bson:"deleted"`
}

Segment describes a group of users.

Deprecated: this type is for internal use and will be moved to another package in a future version.

func (*Segment) Clone

func (s *Segment) Clone() VersionedData

Clone returns a copy of a segment

func (Segment) ContainsUser

func (s Segment) ContainsUser(user User) (bool, *SegmentExplanation)

ContainsUser returns whether a user belongs to the segment

func (*Segment) GetKey

func (s *Segment) GetKey() string

GetKey returns the unique key describing a segment

func (*Segment) GetVersion

func (s *Segment) GetVersion() int

GetVersion returns the version of the segment

func (*Segment) IsDeleted

func (s *Segment) IsDeleted() bool

IsDeleted returns whether a flag has been deleted

type SegmentExplanation deprecated

type SegmentExplanation struct {
	Kind        string
	MatchedRule *SegmentRule
}

SegmentExplanation describes a rule that determines whether a user was included in or excluded from a segment.

Deprecated: this type is for internal use and will be removed in a future version.

type SegmentRule deprecated

type SegmentRule struct {
	Id       string   `json:"id,omitempty" bson:"id,omitempty"`
	Clauses  []Clause `json:"clauses" bson:"clauses"`
	Weight   *int     `json:"weight,omitempty" bson:"weight,omitempty"`
	BucketBy *string  `json:"bucketBy,omitempty" bson:"bucketBy,omitempty"`
}

SegmentRule describes a set of rules in a Segment.

Deprecated: this type is for internal use and will be moved to another package in a future version.

func (SegmentRule) MatchesUser

func (r SegmentRule) MatchesUser(user User, key, salt string) bool

MatchesUser returns whether a rule applies to a user

type SegmentVersionedDataKind deprecated

type SegmentVersionedDataKind struct{}

SegmentVersionedDataKind implements VersionedDataKind and provides methods to build storage engine for segments.

Deprecated: this type is for internal use and will be moved to another package in a future version.

Segments is convenience variable to access an instance of SegmentVersionedDataKind.

Deprecated: this variable is for internal use and will be moved to another package in a future version.

func (SegmentVersionedDataKind) GetDefaultItem

func (sk SegmentVersionedDataKind) GetDefaultItem() interface{}

GetDefaultItem returns a default segment representation

func (SegmentVersionedDataKind) GetNamespace

func (sk SegmentVersionedDataKind) GetNamespace() string

GetNamespace returns the a unique namespace identifier for feature flag objects

func (SegmentVersionedDataKind) MakeDeletedItem

func (sk SegmentVersionedDataKind) MakeDeletedItem(key string, version int) VersionedData

MakeDeletedItem returns representation of a deleted segment

func (SegmentVersionedDataKind) String

func (sk SegmentVersionedDataKind) String() string

String returns the namespace

type Target deprecated

type Target struct {
	Values    []string `json:"values" bson:"values"`
	Variation int      `json:"variation" bson:"variation"`
}

Target describes a set of users who will receive a specific variation.

Deprecated: this type is for internal use and will be moved to another package in a future version.

type TargetRule

type TargetRule struct {
	Attribute string        `json:"attribute"`
	Op        Operator      `json:"op"`
	Values    []interface{} `json:"values"`
}

TargetRule describes an individual targeting rule

type UpdateProcessor

type UpdateProcessor interface {
	Initialized() bool
	Close() error
	Start(closeWhenReady chan<- struct{})
}

UpdateProcessor describes the interface for an object that receives feature flag data.

type UpdateProcessorFactory

type UpdateProcessorFactory func(sdkKey string, config Config) (UpdateProcessor, error)

UpdateProcessorFactory is a function that creates an UpdateProcessor.

type User

type User struct {
	// Key is the unique key of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Key *string `json:"key,omitempty" bson:"key,omitempty"`
	// SecondaryKey is the secondary key of the user.
	//
	// This affects feature flag targeting (https://docs.launchdarkly.com/docs/targeting-users#section-targeting-rules-based-on-user-attributes)
	// as follows: if you have chosen to bucket users by a specific attribute, the secondary key (if set)
	// is used to further distinguish between users who are otherwise identical according to that attribute.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Secondary *string `json:"secondary,omitempty" bson:"secondary,omitempty"`
	// Ip is the IP address attribute of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Ip *string `json:"ip,omitempty" bson:"ip,omitempty"`
	// Country is the country attribute of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Country *string `json:"country,omitempty" bson:"country,omitempty"`
	// Email is the email address attribute of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Email *string `json:"email,omitempty" bson:"email,omitempty"`
	// FirstName is the first name attribute of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	FirstName *string `json:"firstName,omitempty" bson:"firstName,omitempty"`
	// LastName is the last name attribute of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	LastName *string `json:"lastName,omitempty" bson:"lastName,omitempty"`
	// Avatar is the avatar URL attribute of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Avatar *string `json:"avatar,omitempty" bson:"avatar,omitempty"`
	// Name is the name attribute of the user.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Name *string `json:"name,omitempty" bson:"name,omitempty"`
	// Anonymous indicates whether the user is anonymous.
	//
	// If a user is anonymous, the user key will not appear on your LaunchDarkly dashboard.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Anonymous *bool `json:"anonymous,omitempty" bson:"anonymous,omitempty"`
	// Custom is the user's map of custom attribute names and values.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Custom *map[string]interface{} `json:"custom,omitempty" bson:"custom,omitempty"`
	// Derived is used internally by the SDK.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	Derived map[string]*DerivedAttribute `json:"derived,omitempty" bson:"derived,omitempty"`

	// PrivateAttributes contains a list of attribute names that were included in the user,
	// but were marked as private. As such, these attributes are not included in the fields above.
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	PrivateAttributes []string `json:"privateAttrs,omitempty" bson:"privateAttrs,omitempty"`

	// This contains list of attributes to keep private, whether they appear at the top-level or Custom
	// The attribute "key" is always sent regardless of whether it is in this list, and "custom" cannot be used to
	// eliminate all custom attributes
	//
	// Deprecated: Direct access to User fields is now deprecated in favor of UserBuilder. In a future version,
	// User fields will be private and only accessible via getter methods.
	PrivateAttributeNames []string `json:"-" bson:"-"`
}

A User contains specific attributes of a user browsing your site. The only mandatory property property is the Key, which must uniquely identify each user. For authenticated users, this may be a username or e-mail address. For anonymous users, this could be an IP address or session ID.

Besides the mandatory Key, User supports two kinds of optional attributes: interpreted attributes (e.g. Ip and Country) and custom attributes. LaunchDarkly can parse interpreted attributes and attach meaning to them. For example, from an IP address, LaunchDarkly can do a geo IP lookup and determine the user's country.

Custom attributes are not parsed by LaunchDarkly. They can be used in custom rules-- for example, a custom attribute such as "customer_ranking" can be used to launch a feature to the top 10% of users on a site.

User fields will be made private in the future, accessible only via getter methods, to prevent unsafe modification of users after they are created. The preferred method of constructing a User is to use either a simple constructor (NewUser, NewAnonymousUser) or the builder pattern with NewUserBuilder. If you do set the User fields directly, it is important not to change any map/slice elements, and not change a string that is pointed to by an existing pointer, after the User has been passed to any SDK methods; otherwise, flag evaluations and analytics events may refer to the wrong user properties (or, in the case of a map, you may even cause a concurrent modification panic).

func NewAnonymousUser

func NewAnonymousUser(key string) User

NewAnonymousUser creates a new anonymous user identified by the given key.

func NewUser

func NewUser(key string) User

NewUser creates a new user identified by the given key.

func (User) Equal

func (u User) Equal(other User) bool

Equal tests whether two users have equal attributes.

Regular struct equality comparison is not allowed for User because it can contain slices and maps. This method is faster than using reflect.DeepEqual(), and also correctly ignores insignificant differences in the internal representation of the attributes.

func (User) GetAnonymous

func (u User) GetAnonymous() bool

GetAnonymous() returns the anonymous attribute of the user.

If a user is anonymous, the user key will not appear on your LaunchDarkly dashboard.

func (User) GetAnonymousOptional

func (u User) GetAnonymousOptional() (bool, bool)

GetAnonymousOptional() returns the anonymous attribute of the user, with a second value indicating whether that attribute was defined for the user or not.

func (User) GetAvatar

func (u User) GetAvatar() ldvalue.OptionalString

GetAvatar() returns the avatar URL attribute of the user, if any.

func (User) GetCountry

func (u User) GetCountry() ldvalue.OptionalString

GetCountry() returns the country attribute of the user, if any.

func (User) GetCustom

func (u User) GetCustom(attrName string) (ldvalue.Value, bool)

GetCustom() returns a custom attribute of the user by name. The boolean second return value indicates whether any value was set for this attribute or not.

The value is returned using the ldvalue.Value type, which can contain any type supported by JSON: boolean, number, string, array (slice), or object (map). Use Value methods to access the value as the desired type, rather than casting it. If the attribute did not exist, the value will be ldvalue.Null() and the second return value will be false.

func (User) GetCustomKeys

func (u User) GetCustomKeys() []string

GetCustomKeys() returns the keys of all custom attributes that have been set on this user.

func (User) GetEmail

func (u User) GetEmail() ldvalue.OptionalString

GetEmail() returns the email address attribute of the user, if any.

func (User) GetFirstName

func (u User) GetFirstName() ldvalue.OptionalString

GetFirstName() returns the first name attribute of the user, if any.

func (User) GetIP

func (u User) GetIP() ldvalue.OptionalString

GetIP() returns the IP address attribute of the user, if any.

func (User) GetKey

func (u User) GetKey() string

GetKey gets the unique key of the user.

func (User) GetLastName

func (u User) GetLastName() ldvalue.OptionalString

GetLastName() returns the last name attribute of the user, if any.

func (User) GetName

func (u User) GetName() ldvalue.OptionalString

GetName() returns the full name attribute of the user, if any.

func (User) GetSecondaryKey

func (u User) GetSecondaryKey() ldvalue.OptionalString

GetSecondaryKey returns the secondary key of the user, if any.

This affects feature flag targeting (https://docs.launchdarkly.com/docs/targeting-users#section-targeting-rules-based-on-user-attributes) as follows: if you have chosen to bucket users by a specific attribute, the secondary key (if set) is used to further distinguish between users who are otherwise identical according to that attribute.

func (User) String

func (u User) String() string

String returns a simple string representation of a user.

type UserBuilder

type UserBuilder interface {
	// Key changes the unique key for the user being built.
	Key(value string) UserBuilder

	// Secondary sets the secondary key attribute for the user being built.
	//
	// This affects feature flag targeting (https://docs.launchdarkly.com/docs/targeting-users#section-targeting-rules-based-on-user-attributes)
	// as follows: if you have chosen to bucket users by a specific attribute, the secondary key (if set)
	// is used to further distinguish between users who are otherwise identical according to that attribute.
	Secondary(value string) UserBuilderCanMakeAttributePrivate

	// IP sets the IP address attribute for the user being built.
	IP(value string) UserBuilderCanMakeAttributePrivate

	// Country sets the country attribute for the user being built.
	Country(value string) UserBuilderCanMakeAttributePrivate

	// Email sets the email attribute for the user being built.
	Email(value string) UserBuilderCanMakeAttributePrivate

	// FirstName sets the first name attribute for the user being built.
	FirstName(value string) UserBuilderCanMakeAttributePrivate

	// LastName sets the last name attribute for the user being built.
	LastName(value string) UserBuilderCanMakeAttributePrivate

	// Avatar sets the avatar URL attribute for the user being built.
	Avatar(value string) UserBuilderCanMakeAttributePrivate

	// Name sets the full name attribute for the user being built.
	Name(value string) UserBuilderCanMakeAttributePrivate

	// Anonymous sets the anonymous attribute for the user being built.
	//
	// If a user is anonymous, the user key will not appear on your LaunchDarkly dashboard.
	Anonymous(value bool) UserBuilder

	// Custom sets a custom attribute for the user being built.
	//
	//     user := NewUserBuilder("user-key").
	//         Custom("custom-attr-name", ldvalue.String("some-string-value")).AsPrivateAttribute().
	//         Build()
	Custom(name string, value ldvalue.Value) UserBuilderCanMakeAttributePrivate

	// Build creates a User from the current UserBuilder properties.
	//
	// The User is independent of the UserBuilder once you have called Build(); modifying the UserBuilder
	// will not affect an already-created User.
	Build() User
}

UserBuilder is a mutable object that uses the Builder pattern to specify properties for a User. This is the preferred method for constructing a User; direct access to User fields will be removed in a future version.

Obtain an instance of UserBuilder by calling NewUserBuilder, then call setter methods such as Name to specify any additional user properties, then call Build() to construct the User. All of the UserBuilder setters return a reference the same builder, so they can be chained together:

user := NewUserBuilder("user-key").Name("Bob").Email("test@example.com").Build()

Setters for user attributes that can be designated private return the type UserBuilderCanMakeAttributePrivate, so you can chain the AsPrivateAttribute method:

user := NewUserBuilder("user-key").Name("Bob").AsPrivateAttribute().Build() // Name is now private

A UserBuilder should not be accessed by multiple goroutines at once.

func NewUserBuilder

func NewUserBuilder(key string) UserBuilder

NewUserBuilder constructs a new UserBuilder, specifying the user key.

For authenticated users, the key may be a username or e-mail address. For anonymous users, this could be an IP address or session ID.

func NewUserBuilderFromUser

func NewUserBuilderFromUser(fromUser User) UserBuilder

NewUserBuilderFromUser constructs a new UserBuilder, copying all attributes from an existing user. You may then call setter methods on the new UserBuilder to modify those attributes.

type UserBuilderCanMakeAttributePrivate

type UserBuilderCanMakeAttributePrivate interface {
	UserBuilder

	// AsPrivateAttribute marks the last attribute that was set on this builder as being a private attribute: that is, its
	// value will not be sent to LaunchDarkly.
	//
	// This action only affects analytics events that are generated by this particular user object. To mark some (or all)
	// user attributes as private for all users, use the Config properties PrivateAttributeName and AllAttributesPrivate.
	//
	// Most attributes can be made private, but Key and Anonymous cannot. This is enforced by the compiler, since the builder
	// methods for attributes that can be made private are the only ones that return UserBuilderCanMakeAttributePrivate;
	// therefore, you cannot write an expression like NewUserBuilder("user-key").AsPrivateAttribute().
	//
	// In this example, FirstName and LastName are marked as private, but Country is not:
	//
	//     user := NewUserBuilder("user-key").
	//         FirstName("Pierre").AsPrivateAttribute().
	//         LastName("Menard").AsPrivateAttribute().
	//         Country("ES").
	//         Build()
	AsPrivateAttribute() UserBuilder

	// AsNonPrivateAttribute marks the last attribute that was set on this builder as not being a private attribute:
	// that is, its value will be sent to LaunchDarkly and can appear on the dashboard.
	//
	// This is the opposite of AsPrivateAttribute(), and has no effect unless you have previously called
	// AsPrivateAttribute() for the same attribute on the same user builder. For more details, see
	// AsPrivateAttribute().
	AsNonPrivateAttribute() UserBuilder
}

UserBuilderCanMakeAttributePrivate is an extension of UserBuilder that allows attributes to be made private via the AsPrivateAttribute() method. All UserBuilderCanMakeAttributePrivate setter methods are the same as UserBuilder, and apply to the original builder.

UserBuilder setter methods for attributes that can be made private always return this interface. See AsPrivateAttribute for details.

type Variation

type Variation struct {
	Value      interface{}  `json:"value"`
	Weight     int          `json:"weight"`
	Targets    []TargetRule `json:"targets"`
	UserTarget *TargetRule  `json:"userTarget,omitempty"`
}

Variation describes what value to return for a user

type VariationOrRollout deprecated

type VariationOrRollout struct {
	Variation *int     `json:"variation,omitempty" bson:"variation,omitempty"`
	Rollout   *Rollout `json:"rollout,omitempty" bson:"rollout,omitempty"`
}

VariationOrRollout contains either the fixed variation or percent rollout to serve. Invariant: one of the variation or rollout must be non-nil.

Deprecated: this type is for internal use and will be moved to another package in a future version.

type VersionedData

type VersionedData interface {
	// GetKey returns the string key for this object.
	GetKey() string
	// GetVersion returns the version number for this object.
	GetVersion() int
	// IsDeleted returns whether or not this object has been deleted.
	IsDeleted() bool
}

VersionedData is a common interface for string-keyed, versioned objects such as feature flags.

type VersionedDataKind

type VersionedDataKind interface {
	// GetNamespace returns a short string that serves as the unique name for the collection of these objects, e.g. "features".
	GetNamespace() string
	// GetDefaultItem return a pointer to a newly created null value of this object type. This is used for JSON unmarshalling.
	GetDefaultItem() interface{}
	// MakeDeletedItem returns a value of this object type with the specified key and version, and Deleted=true.
	MakeDeletedItem(key string, version int) VersionedData
}

VersionedDataKind describes a kind of VersionedData objects that may exist in a store.

type WeightedVariation deprecated

type WeightedVariation struct {
	Variation int `json:"variation" bson:"variation"`
	Weight    int `json:"weight" bson:"weight"` // Ranges from 0 to 100000
}

WeightedVariation describes a fraction of users who will receive a specific variation.

Deprecated: this type is for internal use and will be moved to another package in a future version.

Directories

Path Synopsis
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.
Package ldconsul provides a Consul-backed feature store for the LaunchDarkly Go SDK.
Package ldconsul provides a Consul-backed feature store for the LaunchDarkly Go SDK.
Package lddynamodb provides a DynamoDB-backed feature store for the LaunchDarkly Go SDK.
Package lddynamodb provides a DynamoDB-backed feature store for the LaunchDarkly Go SDK.
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, with automatic reloading.
Package ldfilewatch allows the LaunchDarkly client to read feature flag data from a file, with automatic reloading.
Package ldhttp provides helper functions for custom HTTP configuration.
Package ldhttp provides helper functions for custom HTTP configuration.
Package ldlog contains a logging abstraction used by LaunchDarkly SDK components.
Package ldlog contains a logging abstraction used by LaunchDarkly SDK components.
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 redis provides a Redis-backed persistent feature store for the LaunchDarkly Go SDK.
Package redis provides a Redis-backed persistent feature store for the LaunchDarkly Go SDK.
ldtest
Package ldtest contains types and functions used by SDK unit tests in multiple packages.
Package ldtest contains types and functions used by SDK unit tests in multiple packages.
Package utils contains support code that most users of the SDK will not need to access directly.
Package utils contains support code that most users of the SDK will not need to access directly.

Jump to

Keyboard shortcuts

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