ldclient

package module
v0.0.0-...-e35b473 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2016 License: Apache-2.0 Imports: 20 Imported by: 0

README

LaunchDarkly SDK for Go

Circle CI

Quick setup

  1. Install the SDK with the go tool:

     go get github.com/launchdarkly/go-client
    
  2. Import the LaunchDarkly client:

     import ld "github.com/launchdarkly/go-client"
    
  3. Create a new LDClient with your API key:

     ld_client := ld.MakeClient("YOUR_API_KEY")
    

Your first feature flag

  1. Create a new feature flag on your dashboard

  2. In your application code, use the feature's key to check wthether the flag is on for each user:

     key := "user@test.com"
     show_feature := ld_client.GetFlag("your.flag.key", ld.User{Key: &key,}, false)
     if (show_feature) {
         # application code to show the feature
     } else {
         # the code to run if the feature is off 
     }
    

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.

Contributing

We encourage pull-requests and other contributions from the community. We've also published an SDK contributor's guide that provides a detailed explanation of how our SDKs work.

About LaunchDarkly

Documentation

Index

Constants

View Source
const (
	FEATURE_REQUEST_EVENT = "feature"
	CUSTOM_EVENT          = "custom"
	IDENTIFY_EVENT        = "identify"
)
View Source
const Version string = "0.0.3"

Variables

View Source
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:  1 * time.Second,
	Logger:        log.New(os.Stderr, "[LaunchDarkly]", log.LstdFlags),
	Timeout:       3000 * time.Millisecond,
	Stream:        true,
	FeatureStore:  nil,
	UseLdd:        false,
	SendEvents:    true,
	Offline:       false,
}

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
View Source
var ErrClientNotInitialized = errors.New("Toggle called before LaunchDarkly client initialization completed")
View Source
var ErrInitializationTimeout = errors.New("Timeout encountered waiting for LaunchDarkly client initialization")

Functions

This section is empty.

Types

type BaseEvent

type BaseEvent struct {
	CreationDate uint64 `json:"creationDate"`
	Key          string `json:"key"`
	Kind         string `json:"kind"`
	User         User   `json:"user"`
}

type Clause

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

type Config

type Config struct {
	BaseUri          string
	StreamUri        string
	EventsUri        string
	Capacity         int
	FlushInterval    time.Duration
	SamplingInterval int32
	PollInterval     time.Duration
	Logger           *log.Logger
	Timeout          time.Duration
	Stream           bool
	FeatureStore     FeatureStore
	UseLdd           bool
	SendEvents       bool
	Offline          bool
}

Exposes advanced configuration options for the LaunchDarkly client.

type CustomEvent

type CustomEvent struct {
	BaseEvent
	Data interface{} `json:"data"`
}

func NewCustomEvent

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

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

func (evt CustomEvent) GetBase() BaseEvent

func (CustomEvent) GetKind

func (evt CustomEvent) GetKind() string

type DerivedAttribute

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

The Derived attribute map is for internal use by LaunchDarkly only. Derived attributes sent to LaunchDarkly are ignored.

type Event

type Event interface {
	GetBase() BaseEvent
	GetKind() string
}

type Explanation

type Explanation struct {
	Kind string `json:"kind" bson:"kind"`
	*Target
	*Rule
}

An explanation is either a target or a rule

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

func (Feature) Evaluate

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

func (Feature) EvaluateExplain

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

type FeatureFlag

type FeatureFlag struct {
	Key          string        `json:"key" bson:"key"`
	Version      int           `json:"version" bson:"version"`
	On           bool          `json:"on" bson:"on"`
	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  Rule          `json:"fallthrough" bson:"fallthrough"`
	OffVariation *int          `json:"offVariation" bson:"offVariation"`
	Variations   []interface{} `json:"variations" bson:"variations"`
}

func (FeatureFlag) EvaluateExplain

func (f FeatureFlag) EvaluateExplain(user User) (interface{}, *Explanation)

type FeatureRequestEvent

type FeatureRequestEvent struct {
	BaseEvent
	Value   interface{} `json:"value"`
	Default interface{} `json:"default"`
}

func NewFeatureRequestEvent

func NewFeatureRequestEvent(key string, user User, value, defaultVal interface{}) FeatureRequestEvent

Used to just create the event. Normally, you don't need to call this; the event is created and queued automatically by Toggle.

func (FeatureRequestEvent) GetBase

func (evt FeatureRequestEvent) GetBase() BaseEvent

func (FeatureRequestEvent) GetKind

func (evt FeatureRequestEvent) GetKind() string

type FeatureStore

type FeatureStore interface {
	Get(key string) (*Feature, error)
	All() (map[string]*Feature, error)
	Init(map[string]*Feature) error
	Delete(key string, version int) error
	Upsert(key string, f Feature) error
	Initialized() bool
}

A data structure that maintains the live collection of features. It is used by LaunchDarkly when streaming mode is enabled, and stores feature events returned by the streaming API. Custom FeatureStore implementations can be passed to the LaunchDarkly client via a custom Config object. LaunchDarkly provides two FeatureStore implementations: one backed by an in-memory map, and one backed by Redis. Implementations must be thread-safe.

type IdentifyEvent

type IdentifyEvent struct {
	BaseEvent
}

func NewIdentifyEvent

func NewIdentifyEvent(user User) IdentifyEvent

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

func (IdentifyEvent) GetKind

func (evt IdentifyEvent) GetKind() string

type InMemoryFeatureStore

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

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

func NewInMemoryFeatureStore

func NewInMemoryFeatureStore() *InMemoryFeatureStore

Creates a new in-memory FeatureStore instance.

func (*InMemoryFeatureStore) All

func (store *InMemoryFeatureStore) All() (map[string]*Feature, error)

func (*InMemoryFeatureStore) Delete

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

func (*InMemoryFeatureStore) Get

func (store *InMemoryFeatureStore) Get(key string) (*Feature, error)

func (*InMemoryFeatureStore) Init

func (store *InMemoryFeatureStore) Init(fs map[string]*Feature) error

func (*InMemoryFeatureStore) Initialized

func (store *InMemoryFeatureStore) Initialized() bool

func (*InMemoryFeatureStore) Upsert

func (store *InMemoryFeatureStore) Upsert(key string, f Feature) error

type LDClient

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

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

func MakeClient

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

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(apiKey string, config Config, waitFor time.Duration) (*LDClient, error)

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

func (client *LDClient) Close()

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

func (*LDClient) Float64Variation

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

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.

func (*LDClient) Flush

func (client *LDClient) Flush()

Immediately flushes queued events.

func (*LDClient) Identify

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

func (*LDClient) Initialized

func (client *LDClient) Initialized() bool

Returns whether the LaunchDarkly client is initialized.

func (*LDClient) IntVariation

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

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.

func (*LDClient) IsOffline

func (client *LDClient) IsOffline() bool

Returns whether the LaunchDarkly client is in offline mode.

func (*LDClient) Toggle

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

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.

func (*LDClient) Track

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

Tracks 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 Operator

type Operator string

type Rollout

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

type Rule

type Rule struct {
	Clauses   []Clause `json:"clauses,omitempty" bson:"clauses,omitempty"`
	Variation *int     `json:"variation,omitempty" bson:"variation,omitempty"`
	Rollout   *Rollout `json:"rollout,omitempty" bson:"rollout,omitempty"`
}

Expresses a set of AND-ed matching conditions for a user, along with either the fixed variation or percent rollout to serve if the conditions match. Invariant: one of the variation or rollout must be non-nil.

type Target

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

type TargetRule

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

type User

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

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.

type Variation

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

type WeightedVariation

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

Directories

Path Synopsis
Godeps
_workspace/src/github.com/facebookgo/httpcontrol
Package httpcontrol allows a HTTP transport supporting connection pooling, timeouts & retries.
Package httpcontrol allows a HTTP transport supporting connection pooling, timeouts & retries.
_workspace/src/github.com/facebookgo/httpcontrol/httpcache
Package httpcache provides a cache enabled http Transport.
Package httpcache provides a cache enabled http Transport.
_workspace/src/github.com/garyburd/redigo/internal/redistest
Package redistest contains utilities for writing Redigo tests.
Package redistest contains utilities for writing Redigo tests.
_workspace/src/github.com/garyburd/redigo/redis
Package redis is a client for the Redis database.
Package redis is a client for the Redis database.
_workspace/src/github.com/gregjones/httpcache
Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses.
Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses.
_workspace/src/github.com/gregjones/httpcache/diskcache
Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage
Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage
_workspace/src/github.com/gregjones/httpcache/memcache
Package memcache provides an implementation of httpcache.Cache that uses gomemcache to store cached responses.
Package memcache provides an implementation of httpcache.Cache that uses gomemcache to store cached responses.
_workspace/src/github.com/launchdarkly/eventsource
Package eventsource implements a client and server to allow streaming data one-way over a HTTP connection using the Server-Sent Events API http://dev.w3.org/html5/eventsource/ The client and server respect the Last-Event-ID header.
Package eventsource implements a client and server to allow streaming data one-way over a HTTP connection using the Server-Sent Events API http://dev.w3.org/html5/eventsource/ The client and server respect the Last-Event-ID header.

Jump to

Keyboard shortcuts

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