go-client.v4: gopkg.in/launchdarkly/go-client.v4 Index | Files | Directories

package ldclient

import "gopkg.in/launchdarkly/go-client.v4"

Index

Package Files

evaluation_detail.go event_processor.go event_summarizer.go events.go events_output.go feature_store.go flag.go flags_state.go ldclient.go legacy_feature.go lru_cache.go operators.go polling.go requestor.go segment.go streaming.go user.go user_filter.go util.go versioned_data.go

Constants

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

Event types

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

SDK endpoints

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.

const Version = "4.7.1"

Version is the client version.

Variables

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

var DefaultConfig = Config{
    BaseUri:               "https://app.launchdarkly.com",
    StreamUri:             "https://stream.launchdarkly.com",
    EventsUri:             "https://events.launchdarkly.com",
    Capacity:              1000,
    FlushInterval:         5 * time.Second,
    PollInterval:          MinimumPollInterval,
    Logger:                log.New(os.Stderr, "[LaunchDarkly]", log.LstdFlags),
    Timeout:               3000 * time.Millisecond,
    Stream:                true,
    FeatureStore:          nil,
    UseLdd:                false,
    SendEvents:            true,
    Offline:               false,
    UserKeysCapacity:      1000,
    UserKeysFlushInterval: 5 * time.Minute,
    UserAgent:             "",
}

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
var OpsList = []Operator{
    OperatorIn,
    OperatorEndsWith,
    OperatorStartsWith,
    OperatorMatches,
    OperatorContains,
    OperatorLessThan,
    OperatorLessThanOrEqual,
    OperatorGreaterThan,
    OperatorGreaterThanOrEqual,
    OperatorBefore,
    OperatorAfter,
    OperatorSegmentMatch,
    OperatorSemVerEqual,
    OperatorSemVerLessThan,
    OperatorSemVerGreaterThan,
}

OpsList is the list of available operators

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.

func MakeAllVersionedDataMap Uses

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

func ParseFloat64 Uses

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.

func ParseTime Uses

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

func ToJsonRawMessage Uses

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

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

type BaseEvent Uses

type BaseEvent struct {
    CreationDate uint64
    User         User
}

BaseEvent provides properties common to all events.

type Clause Uses

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

type Config Uses

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).
    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
    Logger Logger
    // 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. See NewInMemoryFeatureStore (the default) and the redis, ldconsul, and lddynamodb packages.
    FeatureStore FeatureStore
    // 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 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
    // 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
    UserAgent             string
}

Config exposes advanced configuration options for the LaunchDarkly client.

type CustomEvent Uses

type CustomEvent struct {
    BaseEvent
    Key  string
    Data interface{}
}

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

func NewCustomEvent Uses

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.

func (CustomEvent) GetBase Uses

func (evt CustomEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type DerivedAttribute Uses

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.

type EvalErrorKind Uses

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 Uses

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 Uses

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: Use EvaluateDetail instead.

type EvaluationDetail Uses

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.
    Value interface{}
    // 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 (EvaluationDetail) IsDefaultValue Uses

func (d EvaluationDetail) IsDefaultValue() bool

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

type EvaluationReason Uses

type EvaluationReason interface {
    // GetKind describes the general category of the reason.
    GetKind() EvalReasonKind
}

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

type EvaluationReasonContainer Uses

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 Uses

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

MarshalJSON implements custom JSON serialization for EvaluationReasonContainer.

func (*EvaluationReasonContainer) UnmarshalJSON Uses

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

UnmarshalJSON implements custom JSON deserialization for EvaluationReasonContainer.

type EvaluationReasonError Uses

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.

func (EvaluationReasonError) GetKind Uses

func (r EvaluationReasonError) GetKind() EvalReasonKind

func (EvaluationReasonError) String Uses

func (r EvaluationReasonError) String() string

type EvaluationReasonFallthrough Uses

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.

func (EvaluationReasonFallthrough) GetKind Uses

func (r EvaluationReasonFallthrough) GetKind() EvalReasonKind

func (EvaluationReasonFallthrough) String Uses

func (r EvaluationReasonFallthrough) String() string

type EvaluationReasonOff Uses

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

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

func (EvaluationReasonOff) GetKind Uses

func (r EvaluationReasonOff) GetKind() EvalReasonKind

func (EvaluationReasonOff) String Uses

func (r EvaluationReasonOff) String() string

type EvaluationReasonPrerequisiteFailed Uses

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.

func (EvaluationReasonPrerequisiteFailed) GetKind Uses

func (r EvaluationReasonPrerequisiteFailed) GetKind() EvalReasonKind

func (EvaluationReasonPrerequisiteFailed) String Uses

func (r EvaluationReasonPrerequisiteFailed) String() string

type EvaluationReasonRuleMatch Uses

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.

func (EvaluationReasonRuleMatch) GetKind Uses

func (r EvaluationReasonRuleMatch) GetKind() EvalReasonKind

func (EvaluationReasonRuleMatch) String Uses

func (r EvaluationReasonRuleMatch) String() string

type EvaluationReasonTargetMatch Uses

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

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

func (EvaluationReasonTargetMatch) GetKind Uses

func (r EvaluationReasonTargetMatch) GetKind() EvalReasonKind

func (EvaluationReasonTargetMatch) String Uses

func (r EvaluationReasonTargetMatch) String() string

type Event Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

Evaluate returns the value of a feature for a specified user

func (Feature) EvaluateExplain Uses

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 Uses

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"`
    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:"-"`
}

FeatureFlag describes an individual feature flag

func (*FeatureFlag) Clone Uses

func (f *FeatureFlag) Clone() VersionedData

Clone returns a copy of a flag

func (FeatureFlag) Evaluate Uses

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: Use EvaluateDetail instead.

func (FeatureFlag) EvaluateDetail Uses

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.

func (FeatureFlag) EvaluateExplain Uses

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: Use EvaluateDetail instead.

func (*FeatureFlag) GetKey Uses

func (f *FeatureFlag) GetKey() string

GetKey returns the string key for the feature flag

func (*FeatureFlag) GetVersion Uses

func (f *FeatureFlag) GetVersion() int

GetVersion returns the version of a flag

func (*FeatureFlag) IsDeleted Uses

func (f *FeatureFlag) IsDeleted() bool

IsDeleted returns whether a flag has been deleted

type FeatureFlagVersionedDataKind Uses

type FeatureFlagVersionedDataKind struct{}

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

var Features FeatureFlagVersionedDataKind

Features is convenience variable to access an instance of FeatureFlagVersionedDataKind

func (FeatureFlagVersionedDataKind) GetDefaultItem Uses

func (fk FeatureFlagVersionedDataKind) GetDefaultItem() interface{}

GetDefaultItem returns a default feature flag representation

func (FeatureFlagVersionedDataKind) GetNamespace Uses

func (fk FeatureFlagVersionedDataKind) GetNamespace() string

GetNamespace returns the a unique namespace identifier for feature flag objects

func (FeatureFlagVersionedDataKind) MakeDeletedItem Uses

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

MakeDeletedItem returns representation of a deleted flag

func (FeatureFlagVersionedDataKind) String Uses

func (fk FeatureFlagVersionedDataKind) String() string

String returns the namespace

type FeatureFlagsState Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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.

func (FeatureRequestEvent) GetBase Uses

func (evt FeatureRequestEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type FeatureStore Uses

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 FlagsStateOption Uses

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 HttpStatusError Uses

type HttpStatusError struct {
    Message string
    Code    int
}

HttpStatusError describes an http error

func (HttpStatusError) Error Uses

func (e HttpStatusError) Error() string

Error returns a the error message for an http status error

type IdentifyEvent Uses

type IdentifyEvent struct {
    BaseEvent
}

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

func NewIdentifyEvent Uses

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 Uses

func (evt IdentifyEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type InMemoryFeatureStore Uses

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 Uses

func NewInMemoryFeatureStore(logger Logger) *InMemoryFeatureStore

NewInMemoryFeatureStore creates a new in-memory FeatureStore instance.

func (*InMemoryFeatureStore) All Uses

func (store *InMemoryFeatureStore) All(kind VersionedDataKind) (map[string]VersionedData, error)

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

func (*InMemoryFeatureStore) Delete Uses

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 Uses

func (store *InMemoryFeatureStore) Get(kind VersionedDataKind, key string) (VersionedData, error)

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

func (*InMemoryFeatureStore) Init Uses

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 Uses

func (store *InMemoryFeatureStore) Initialized() bool

Initialized returns whether the store has been initialized with data

func (*InMemoryFeatureStore) Upsert Uses

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 Uses

type IndexEvent struct {
    BaseEvent
}

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

func (IndexEvent) GetBase Uses

func (evt IndexEvent) GetBase() BaseEvent

GetBase returns the BaseEvent

type LDClient Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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, the client hasn't completed initialization, or the feature is turned off and has no off variation.

func (*LDClient) BoolVariationDetail Uses

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 Uses

func (client *LDClient) Close() error

Close shuts down the LaunchDarkly client. After calling this, the LaunchDarkly client should no longer be used.

func (*LDClient) Evaluate Uses

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

Evaluate returns the value of a feature for a specified user

func (*LDClient) Float64Variation Uses

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 Uses

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 Uses

func (client *LDClient) Flush()

Flush immediately flushes queued events.

func (*LDClient) Identify Uses

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

Identify reports details about a a user.

func (*LDClient) Initialized Uses

func (client *LDClient) Initialized() bool

Initialized returns whether the LaunchDarkly client is initialized.

func (*LDClient) IntVariation Uses

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.

func (*LDClient) IntVariationDetail Uses

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 Uses

func (client *LDClient) IsOffline() bool

IsOffline returns whether the LaunchDarkly client is in offline mode.

func (*LDClient) JsonVariation Uses

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

JsonVariation returns the value of a feature flag (whose variations are JSON) for the given user. Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off.

func (*LDClient) JsonVariationDetail Uses

func (client *LDClient) JsonVariationDetail(key string, user User, defaultVal json.RawMessage) (json.RawMessage, 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) SecureModeHash Uses

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 Uses

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 Uses

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 Uses

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

Track reports that a user has performed an event. Custom data can be attached to the event, and is serialized to JSON using the encoding/json package (http://golang.org/pkg/encoding/json/).

type Logger Uses

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

Logger is a generic logger interface.

type Operator Uses

type Operator string

Operator describes an operator for a clause

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 Uses

func (op Operator) Name() string

Name returns the string name for an operator

type Prerequisite Uses

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

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

type Rollout Uses

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

type Rule Uses

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

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

type Segment Uses

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

func (*Segment) Clone Uses

func (s *Segment) Clone() VersionedData

Clone returns a copy of a segment

func (Segment) ContainsUser Uses

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

ContainsUser returns whether a user belongs to the segment

func (*Segment) GetKey Uses

func (s *Segment) GetKey() string

GetKey returns the unique key describing a segment

func (*Segment) GetVersion Uses

func (s *Segment) GetVersion() int

GetVersion returns the version of the segment

func (*Segment) IsDeleted Uses

func (s *Segment) IsDeleted() bool

IsDeleted returns whether a flag has been deleted

type SegmentExplanation Uses

type SegmentExplanation struct {
    Kind        string
    MatchedRule *SegmentRule
}

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

type SegmentRule Uses

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 clauses that

func (SegmentRule) MatchesUser Uses

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

MatchesUser returns whether a rule applies to a user

type SegmentVersionedDataKind Uses

type SegmentVersionedDataKind struct{}

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

var Segments SegmentVersionedDataKind

Segments is convenience variable to access an instance of SegmentVersionedDataKind

func (SegmentVersionedDataKind) GetDefaultItem Uses

func (sk SegmentVersionedDataKind) GetDefaultItem() interface{}

GetDefaultItem returns a default segment representation

func (SegmentVersionedDataKind) GetNamespace Uses

func (sk SegmentVersionedDataKind) GetNamespace() string

GetNamespace returns the a unique namespace identifier for feature flag objects

func (SegmentVersionedDataKind) MakeDeletedItem Uses

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

MakeDeletedItem returns representation of a deleted segment

func (SegmentVersionedDataKind) String Uses

func (sk SegmentVersionedDataKind) String() string

String returns the namespace

type Target Uses

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

type TargetRule Uses

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

TargetRule describes an individual targeting rule

type UpdateProcessor Uses

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 Uses

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

UpdateProcessorFactory is a function that creates an UpdateProcessor.

type User Uses

type User struct {
    Key       *string                      `json:"key,omitempty" bson:"key,omitempty"`
    Secondary *string                      `json:"secondary,omitempty" bson:"secondary,omitempty"`
    Ip        *string                      `json:"ip,omitempty" bson:"ip,omitempty"`
    Country   *string                      `json:"country,omitempty" bson:"country,omitempty"`
    Email     *string                      `json:"email,omitempty" bson:"email,omitempty"`
    FirstName *string                      `json:"firstName,omitempty" bson:"firstName,omitempty"`
    LastName  *string                      `json:"lastName,omitempty" bson:"lastName,omitempty"`
    Avatar    *string                      `json:"avatar,omitempty" bson:"avatar,omitempty"`
    Name      *string                      `json:"name,omitempty" bson:"name,omitempty"`
    Anonymous *bool                        `json:"anonymous,omitempty" bson:"anonymous,omitempty"`
    Custom    *map[string]interface{}      `json:"custom,omitempty" bson:"custom,omitempty"`
    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.
    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
    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.

func NewAnonymousUser Uses

func NewAnonymousUser(key string) User

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

func NewUser Uses

func NewUser(key string) User

NewUser creates a new user identified by the given key.

type Variation Uses

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 Uses

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.

type VersionedData Uses

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 Uses

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 Uses

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

Directories

PathSynopsis
ldconsulPackage ldconsul provides a Consul-backed feature store for the LaunchDarkly Go SDK.
lddynamodbPackage lddynamodb provides a DynamoDB-backed feature store for the LaunchDarkly Go SDK.
ldfiledataPackage ldfiledata allows the LaunchDarkly client to read feature flag data from a file.
ldfilewatchPackage ldfilewatch allows the LaunchDarkly client to read feature flag data from a file, with automatic reloading.
redisPackage redis provides a Redis-backed persistent feature store for the LaunchDarkly Go SDK.
utilsPackage utils contains support code that most users of the SDK will not need to access directly.

Package ldclient imports 25 packages (graph) and is imported by 23 packages. Updated 2019-03-14. Refresh now. Tools for package owners.