func BuildFeatures(v interface{}) map[string]*Feature
BuildFeatures creates a Feature array from a generic JSON value.
func ConfigureCache(c Cache)
func ConfigureCacheBackgroundSync(bgSync bool)
func SetLogger(userLogger Logger)
SetLogger sets up the logging interface used throughout. The idea here is to provide developers with the option of handling errors and warnings in a strict way during development and a lenient way in production. For example, in development, setting a logger that prints a message for all logged output and panics on any logged warning or error might be appropriate, while in production, it would make more sense to log only warnings and errors and to proceed without halting. All GrowthBook SDK functions leave values in a sensible default state after errors, so production systems can essentially ignore any errors.
Assignment is used for recording subscription information.
type Assignment struct { Experiment *Experiment Result *Result }
Attributes is an arbitrary JSON object containing user and request attributes.
type Attributes map[string]interface{}
type Cache interface { Initialize() Clear() Get(key RepositoryKey) *CacheEntry Set(key RepositoryKey, entry *CacheEntry) }
type CacheEntry struct { Data *FeatureAPIResponse `json:"data"` Version time.Time `json:"version"` StaleAt time.Time `json:"stale_at"` }
Condition represents conditions used to target features/experiments to specific users.
type Condition interface { Eval(attrs Attributes) bool }
func BuildCondition(cond map[string]interface{}) Condition
BuildCondition creates a Condition value from a JSON object represented as a Go map.
func ParseCondition(data []byte) Condition
ParseCondition creates a Condition value from raw JSON input.
Context contains the options for creating a new GrowthBook instance.
type Context struct { Enabled bool Attributes Attributes URL *url.URL Features FeatureMap ForcedVariations ForcedVariationsMap QAMode bool DevMode bool TrackingCallback ExperimentCallback OnFeatureUsage FeatureUsageCallback UserAttributes Attributes Groups map[string]bool APIHost string ClientKey string DecryptionKey string Overrides ExperimentOverrides CacheTTL time.Duration }
func BuildContext(dict map[string]interface{}) *Context
BuildContext creates a Context value from a JSON object represented as a Go map.
func NewContext() *Context
NewContext creates a context with default settings: enabled, but all other fields empty.
func ParseContext(data []byte) *Context
ParseContext creates a Context value from raw JSON input.
func (ctx *Context) ForceVariation(key string, variation int)
func (ctx *Context) UnforceVariation(key string)
func (ctx *Context) WithAPIHost(host string) *Context
WithAPIHost sets the API host of a context.
func (ctx *Context) WithAttributes(attributes Attributes) *Context
WithAttributes sets the attributes for a context.
func (ctx *Context) WithCacheTTL(ttl time.Duration) *Context
WithCacheTTL sets the TTL for the feature cache.
func (ctx *Context) WithClientKey(key string) *Context
WithClientKey sets the API client key of a context.
func (ctx *Context) WithDecryptionKey(key string) *Context
WithDecryptionKey sets the decryption key of a context.
func (ctx *Context) WithDevMode(devMode bool) *Context
WithDevMode can be used to enable or disable the development mode for a context.
func (ctx *Context) WithEnabled(enabled bool) *Context
WithEnabled sets the enabled flag for a context.
func (ctx *Context) WithFeatureUsageCallback(callback FeatureUsageCallback) *Context
WithFeatureUsageCallback is used to set a feature usage callback for a context.
func (ctx *Context) WithFeatures(features FeatureMap) *Context
WithFeatures sets the features for a context (as a value of type FeatureMap, which is a map from feature names to *Feature values).
func (ctx *Context) WithForcedVariations(forcedVariations ForcedVariationsMap) *Context
WithForcedVariations sets the forced variations for a context (as a value of type ForcedVariationsMap, which is a map from experiment keys to variation indexes).
func (ctx *Context) WithGroups(groups map[string]bool) *Context
WithGroups sets the groups map of a context.
func (ctx *Context) WithOverrides(overrides ExperimentOverrides) *Context
WithOverrides sets the experiment overrides of a context.
func (ctx *Context) WithQAMode(qaMode bool) *Context
WithQAMode can be used to enable or disable the QA mode for a context.
func (ctx *Context) WithTrackingCallback(callback ExperimentCallback) *Context
WithTrackingCallback is used to set a tracking callback for a context.
func (ctx *Context) WithURL(url *url.URL) *Context
WithURL sets the URL for a context.
func (ctx *Context) WithUserAttributes(attributes Attributes) *Context
WithUserAttributes sets the user attributes for a context.
DevLogger is a logger instance suitable for use in development. It prints all logged messages to standard output, and exits on errors.
type DevLogger struct{}
func (log *DevLogger) Error(msg string, args ...interface{})
func (log *DevLogger) Errorf(format string, args ...interface{})
func (log *DevLogger) Info(msg string, args ...interface{})
func (log *DevLogger) Infof(format string, args ...interface{})
func (log *DevLogger) Warn(msg string, args ...interface{})
func (log *DevLogger) Warnf(format string, args ...interface{})
Experiment defines a single experiment.
type Experiment struct { Key string Variations []FeatureValue Ranges []Range Meta []VariationMeta Filters []Filter Seed string Name string Phase string URLPatterns []URLTarget Weights []float64 Condition Condition Coverage *float64 Include func() bool Namespace *Namespace Force *int HashAttribute string HashVersion int Active bool Status ExperimentStatus URL *regexp.Regexp Groups []string }
func BuildExperiment(dict map[string]interface{}) *Experiment
BuildExperiment creates an Experiment value from a JSON object represented as a Go map.
func NewExperiment(key string) *Experiment
NewExperiment creates an experiment with default settings: active, but all other fields empty.
func ParseExperiment(data []byte) *Experiment
ParseExperiment creates an Experiment value from raw JSON input.
func (exp *Experiment) WithActive(active bool) *Experiment
WithActive sets the enabled flag for an experiment.
func (exp *Experiment) WithCondition(condition Condition) *Experiment
WithCondition sets the condition for an experiment.
func (exp *Experiment) WithCoverage(coverage float64) *Experiment
WithCoverage sets the coverage for an experiment.
func (exp *Experiment) WithFilters(filters ...Filter) *Experiment
WithFilters sets the filters for an experiment.
func (exp *Experiment) WithForce(force int) *Experiment
WithForce sets the forced value index for an experiment.
func (exp *Experiment) WithGroups(groups ...string) *Experiment
WithGroups sets the groups for an experiment.
func (exp *Experiment) WithHashAttribute(hashAttribute string) *Experiment
WithHashAttribute sets the hash attribute for an experiment.
func (exp *Experiment) WithHashVersion(hashVersion int) *Experiment
WithHashVersion sets the hash version for an experiment.
func (exp *Experiment) WithIncludeFunction(include func() bool) *Experiment
WithInclude sets the inclusion function for an experiment.
func (exp *Experiment) WithMeta(meta ...VariationMeta) *Experiment
WithMeta sets the meta information for an experiment.
func (exp *Experiment) WithName(name string) *Experiment
WithName sets the name for an experiment.
func (exp *Experiment) WithNamespace(namespace *Namespace) *Experiment
WithNamespace sets the namespace for an experiment.
func (exp *Experiment) WithPhase(phase string) *Experiment
WithPhase sets the phase for an experiment.
func (exp *Experiment) WithRanges(ranges ...Range) *Experiment
WithRanges set the ranges for an experiment.
func (exp *Experiment) WithSeed(seed string) *Experiment
WithSeed sets the hash seed for an experiment.
func (exp *Experiment) WithStatus(status ExperimentStatus) *Experiment
WithStatus sets the status for an experiment.
func (exp *Experiment) WithURL(url *regexp.Regexp) *Experiment
WithURL sets the URL for an experiment.
func (exp *Experiment) WithVariations(variations ...FeatureValue) *Experiment
WithVariations set the feature variations for an experiment.
func (exp *Experiment) WithWeights(weights ...float64) *Experiment
WithWeights set the weights for an experiment.
ExperimentCallback is a callback function that is executed every time a user is included in an Experiment. It is also the type used for subscription functions, which are called whenever Experiment.Run is called and the experiment result changes, independent of whether a user is inncluded in the experiment or not.
type ExperimentCallback func(experiment *Experiment, result *Result)
ExperimentOverride provides the possibility to temporarily override some experiment settings.
type ExperimentOverride struct { Condition Condition Weights []float64 Active *bool Status *ExperimentStatus Force *int Coverage *float64 Groups []string Namespace *Namespace URL *regexp.Regexp }
type ExperimentOverrides map[string]*ExperimentOverride
type ExperimentStatus string
const ( DraftStatus ExperimentStatus = "draft" RunningStatus ExperimentStatus = "running" StoppedStatus ExperimentStatus = "stopped" )
Feature has a default value plus rules than can override the default.
type Feature struct { DefaultValue FeatureValue `json:"defaultValue"` Rules []*FeatureRule `json:"rules"` }
func BuildFeature(val interface{}) *Feature
BuildFeature creates a Feature value from a generic JSON value.
func ParseFeature(data []byte) *Feature
ParseFeature creates a single Feature value from raw JSON input.
type FeatureAPIResponse struct { Status int `json:"status"` Features map[string]*Feature `json:"features"` DateUpdated time.Time `json:"dateUpdated"` EncryptedFeatures string `json:"encryptedFeatures"` }
func BuildFeatureAPIResponse(dict map[string]interface{}) *FeatureAPIResponse
BuildFeatureAPIResponse creates a FeatureAPIResponse value from a generic JSON value.
func ParseFeatureAPIResponse(data []byte) *FeatureAPIResponse
ParseFeature creates a single Feature value from raw JSON input.
func (r *FeatureAPIResponse) MarshalJSON() ([]byte, error)
func (r *FeatureAPIResponse) UnmarshalJSON(data []byte) error
FeatureMap is a map of feature objects, keyed by string feature IDs.
type FeatureMap map[string]*Feature
func BuildFeatureMap(dict map[string]interface{}) FeatureMap
BuildFeatureMap creates a FeatureMap value from a JSON object represented as a Go map.
func ParseFeatureMap(data []byte) FeatureMap
ParseFeatureMap creates a FeatureMap value from raw JSON input.
type FeatureRepoOptions struct { AutoRefresh bool Timeout time.Duration SkipCache bool }
FeatureResult is the result of evaluating a feature.
type FeatureResult struct { Value FeatureValue Source FeatureResultSource On bool Off bool RuleID string Experiment *Experiment ExperimentResult *Result }
func BuildFeatureResult(dict map[string]interface{}) *FeatureResult
BuildFeatureResult creates an FeatureResult value from a JSON object represented as a Go map.
func (fr *FeatureResult) GetValueWithDefault(def FeatureValue) FeatureValue
GetValueWithDefault extracts a value from a FeatureResult with a default.
FeatureResultSource is an enumerated type representing the source of a FeatureResult.
type FeatureResultSource uint
FeatureResultSource values.
const ( UnknownResultSource FeatureResultSource = iota + 1 DefaultValueResultSource ForceResultSource ExperimentResultSource OverrideResultSource )
func ParseFeatureResultSource(source string) FeatureResultSource
ParseFeatureResultSource creates a FeatureResultSource value from its string representation.
FeatureRule overrides the default value of a Feature.
type FeatureRule struct { ID string Condition Condition Force FeatureValue Variations []FeatureValue Weights []float64 Key string HashAttribute string HashVersion int Range *Range Coverage *float64 Namespace *Namespace Ranges []Range Meta []VariationMeta Filters []Filter Seed string Name string Phase string }
func BuildFeatureRule(val interface{}) *FeatureRule
BuildFeatureRule creates an FeatureRule value from a generic JSON value.
FeatureUsageCallback is a callback function that is executed every time a feature is evaluated.
type FeatureUsageCallback func(key string, result *FeatureResult)
FeatureValue is a wrapper around an arbitrary type representing the value of a feature. Features can return any kinds of values, so this is an alias for interface{}.
type FeatureValue interface{}
func BuildFeatureValues(val interface{}) []FeatureValue
BuildFeatureValues creates a FeatureValue array from a generic JSON value.
Filter represents a filter condition for experiment mutual exclusion.
type Filter struct { Attribute string Seed string HashVersion int Ranges []Range }
ForcedVariationsMap is a map that forces an Experiment to always assign a specific variation. Useful for QA.
Keys are the experiment key, values are the array index of the variation.
type ForcedVariationsMap map[string]int
GrowthBook is the main export of the SDK.
type GrowthBook struct {
// contains filtered or unexported fields
}
func New(context *Context) *GrowthBook
New creates a new GrowthBook instance.
func (gb *GrowthBook) Attributes() Attributes
Attributes returns the attributes in a GrowthBook's context, possibly modified by overrides.
func (gb *GrowthBook) ClearSavedResults()
ClearSavedResults clears out any experiment results saved within a GrowthBook instance (used for deciding whether to send data to subscriptions).
func (gb *GrowthBook) ClearTrackingData()
ClearTrackingData clears out records of calls to the experiment tracking callback.
func (gb *GrowthBook) EvalFeature(id string) *FeatureResult
EvalFeature returns the result for a feature identified by a string feature key.
func (gb *GrowthBook) Feature(key string) *FeatureResult
Deprecated: Use EvalFeature instead. Feature returns the result for a feature identified by a string feature key.
func (gb *GrowthBook) Features() FeatureMap
Features returns the features in a GrowthBook's context.
func (gb *GrowthBook) ForceVariation(key string, variation int)
func (gb *GrowthBook) GetAPIInfo() (string, string)
GetAPIInfo gets the hostname and client key for GrowthBook API access.
func (gb *GrowthBook) GetAllResults() map[string]*Assignment
GetAllResults returns a map containing all the latest results from all experiments that have been run, indexed by the experiment key.
func (gb *GrowthBook) GetFeatureValue(key string, defaultValue interface{}) interface{}
GetFeatureValue returns the result for a feature identified by a string feature key, with an explicit default.
func (gb *GrowthBook) IsOff(key string) bool
IsOff determines whether a feature is off.
func (gb *GrowthBook) IsOn(key string) bool
IsOn determines whether a feature is on.
func (gb *GrowthBook) LatestFeatureUpdate() *time.Time
func (gb *GrowthBook) LoadFeatures(options *FeatureRepoOptions)
func (gb *GrowthBook) Ready() bool
Ready returns the ready flag, which indicates that features have been loaded.
func (gb *GrowthBook) RefreshFeatures(options *FeatureRepoOptions)
func (gb *GrowthBook) Run(exp *Experiment) *Result
Run an experiment. (Uses doRun to make wrapping for subscriptions simple.)
func (gb *GrowthBook) Subscribe(callback ExperimentCallback) func()
Subscribe adds a callback that is called every time GrowthBook.Run is called. This is different from the tracking callback since it also fires when a user is not included in an experiment.
func (gb *GrowthBook) UnforceVariation(key string)
func (gb *GrowthBook) WithAPIHost(host string) *GrowthBook
WithAPIHost sets the API host of a context.
func (gb *GrowthBook) WithAttributeOverrides(overrides Attributes) *GrowthBook
WithAttributeOverrides updates the current attribute overrides.
func (gb *GrowthBook) WithAttributes(attrs Attributes) *GrowthBook
WithAttributes updates the attributes in a GrowthBook's context.
func (gb *GrowthBook) WithClientKey(key string) *GrowthBook
WithClientKey sets the API client key of a context.
func (gb *GrowthBook) WithDecryptionKey(key string) *GrowthBook
WithDecryptionKey sets the decryption key of a context.
func (gb *GrowthBook) WithDevMode(devMode bool) *GrowthBook
WithDevMode can be used to enable or disable the development mode for a context.
func (gb *GrowthBook) WithEnabled(enabled bool) *GrowthBook
WithEnabled sets the enabled flag in a GrowthBook's context.
func (gb *GrowthBook) WithEncryptedFeatures(encrypted string, key string) (*GrowthBook, error)
WithEncryptedFeatures updates the features in a GrowthBook's context from encrypted data.
func (gb *GrowthBook) WithFeatureUsageCallback(callback FeatureUsageCallback) *GrowthBook
WithFeatureUsageCallback is used to set a feature usage callback for a context.
func (gb *GrowthBook) WithFeatures(features FeatureMap) *GrowthBook
WithFeatures updates the features in a GrowthBook's context.
func (gb *GrowthBook) WithForcedFeatures(values map[string]interface{}) *GrowthBook
WithForcedFeatures updates the current forced feature values.
func (gb *GrowthBook) WithForcedVariations(forcedVariations ForcedVariationsMap) *GrowthBook
WithForcedVariations sets the forced variations in a GrowthBook's context.
func (gb *GrowthBook) WithGroups(groups map[string]bool) *GrowthBook
WithGroups sets the groups map of a context.
func (gb *GrowthBook) WithQAMode(qaMode bool) *GrowthBook
WithQAMode can be used to enable or disable the QA mode for a context.
func (gb *GrowthBook) WithTrackingCallback(callback ExperimentCallback) *GrowthBook
WithTrackingCallback is used to set a tracking callback for a context.
func (gb *GrowthBook) WithURL(url *url.URL) *GrowthBook
WithURL sets the URL in a GrowthBook's context.
Logger is a common interface for logging information and warning messages (errors are returned directly by SDK functions, but there is some useful "out of band" data that's provided via this interface).
type Logger interface { Error(msg string, args ...interface{}) Errorf(format string, args ...interface{}) Warn(msg string, args ...interface{}) Warnf(format string, args ...interface{}) Info(msg string, args ...interface{}) Infof(format string, args ...interface{}) }
Namespace specifies what part of a namespace an experiment includes. If two experiments are in the same namespace and their ranges don't overlap, they wil be mutually exclusive.
type Namespace struct { ID string Start float64 End float64 }
func BuildNamespace(val interface{}) *Namespace
BuildNamespace creates a Namespace value from a generic JSON value.
func ParseNamespace(data []byte) *Namespace
ParseNamespace creates a Namespace value from raw JSON input.
Range represents a single bucket range.
type Range struct { Min float64 Max float64 }
func (r *Range) InRange(n float64) bool
type RepositoryKey string
Result records the result of running an Experiment given a specific Context.
type Result struct { Value FeatureValue VariationID int Key string Name string Bucket *float64 Passthrough bool InExperiment bool HashUsed bool HashAttribute string HashValue string FeatureID string }
func BuildResult(dict map[string]interface{}) *Result
BuildResult creates an Result value from a JSON object represented as a Go map.
URL match target.
type URLTarget struct { Type URLTargetType Include bool Pattern string }
URL matching supports regular expressions or simple string matches.
type URLTargetType uint
const ( RegexURLTarget URLTargetType = iota SimpleURLTarget = iota )
VariationMeta represents meta-information that can be passed through to tracking callbacks.
type VariationMeta struct { Passthrough bool Key string Name string }