growthbook

package module
v0.0.0-...-015122f Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2024 License: MIT Imports: 22 Imported by: 0

README

GrowthBook Go SDK

Requirements

  • Go version 1.18 or higher (tested with 1.18, 1.19, 1.20)

Installation

go get github.com/growthbook/growthbook-golang

Documentation

Documentation

Overview

Package growthbook provides a Go SDK for the GrowthBook A/B testing and feature flagging service.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildFeatures

func BuildFeatures(v interface{}) map[string]*Feature

BuildFeatures creates a Feature array from a generic JSON value.

func ConfigureCache

func ConfigureCache(c Cache)

func ConfigureCacheBackgroundSync

func ConfigureCacheBackgroundSync(bgSync bool)

func SetLogger

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.

Types

type Assignment

type Assignment struct {
	Experiment *Experiment
	Result     *Result
}

Assignment is used for recording subscription information.

type Attributes

type Attributes map[string]interface{}

Attributes is an arbitrary JSON object containing user and request attributes.

type Cache

type Cache interface {
	Initialize()
	Clear()
	Get(key RepositoryKey) *CacheEntry
	Set(key RepositoryKey, entry *CacheEntry)
}

type CacheEntry

type CacheEntry struct {
	Data    *FeatureAPIResponse `json:"data"`
	Version time.Time           `json:"version"`
	StaleAt time.Time           `json:"stale_at"`
}

type Condition

type Condition interface {
	Eval(attrs Attributes) bool
}

Condition represents conditions used to target features/experiments to specific users.

func BuildCondition

func BuildCondition(cond map[string]interface{}) Condition

BuildCondition creates a Condition value from a JSON object represented as a Go map.

func ParseCondition

func ParseCondition(data []byte) Condition

ParseCondition creates a Condition value from raw JSON input.

type Context

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
}

Context contains the options for creating a new GrowthBook instance.

func BuildContext

func BuildContext(dict map[string]interface{}) *Context

BuildContext creates a Context value from a JSON object represented as a Go map.

func NewContext

func NewContext() *Context

NewContext creates a context with default settings: enabled, but all other fields empty.

func ParseContext

func ParseContext(data []byte) *Context

ParseContext creates a Context value from raw JSON input.

func (*Context) ForceVariation

func (ctx *Context) ForceVariation(key string, variation int)

func (*Context) UnforceVariation

func (ctx *Context) UnforceVariation(key string)

func (*Context) WithAPIHost

func (ctx *Context) WithAPIHost(host string) *Context

WithAPIHost sets the API host of a context.

func (*Context) WithAttributes

func (ctx *Context) WithAttributes(attributes Attributes) *Context

WithAttributes sets the attributes for a context.

func (*Context) WithCacheTTL

func (ctx *Context) WithCacheTTL(ttl time.Duration) *Context

WithCacheTTL sets the TTL for the feature cache.

func (*Context) WithClientKey

func (ctx *Context) WithClientKey(key string) *Context

WithClientKey sets the API client key of a context.

func (*Context) WithDecryptionKey

func (ctx *Context) WithDecryptionKey(key string) *Context

WithDecryptionKey sets the decryption key of a context.

func (*Context) WithDevMode

func (ctx *Context) WithDevMode(devMode bool) *Context

WithDevMode can be used to enable or disable the development mode for a context.

func (*Context) WithEnabled

func (ctx *Context) WithEnabled(enabled bool) *Context

WithEnabled sets the enabled flag for a context.

func (*Context) WithFeatureUsageCallback

func (ctx *Context) WithFeatureUsageCallback(callback FeatureUsageCallback) *Context

WithFeatureUsageCallback is used to set a feature usage callback for a context.

func (*Context) WithFeatures

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 (*Context) WithForcedVariations

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 (*Context) WithGroups

func (ctx *Context) WithGroups(groups map[string]bool) *Context

WithGroups sets the groups map of a context.

func (*Context) WithOverrides

func (ctx *Context) WithOverrides(overrides ExperimentOverrides) *Context

WithOverrides sets the experiment overrides of a context.

func (*Context) WithQAMode

func (ctx *Context) WithQAMode(qaMode bool) *Context

WithQAMode can be used to enable or disable the QA mode for a context.

func (*Context) WithTrackingCallback

func (ctx *Context) WithTrackingCallback(callback ExperimentCallback) *Context

WithTrackingCallback is used to set a tracking callback for a context.

func (*Context) WithURL

func (ctx *Context) WithURL(url *url.URL) *Context

WithURL sets the URL for a context.

func (*Context) WithUserAttributes

func (ctx *Context) WithUserAttributes(attributes Attributes) *Context

WithUserAttributes sets the user attributes for a context.

type DevLogger

type DevLogger struct{}

DevLogger is a logger instance suitable for use in development. It prints all logged messages to standard output, and exits on errors.

func (*DevLogger) Error

func (log *DevLogger) Error(msg string, args ...interface{})

func (*DevLogger) Errorf

func (log *DevLogger) Errorf(format string, args ...interface{})

func (*DevLogger) Info

func (log *DevLogger) Info(msg string, args ...interface{})

func (*DevLogger) Infof

func (log *DevLogger) Infof(format string, args ...interface{})

func (*DevLogger) Warn

func (log *DevLogger) Warn(msg string, args ...interface{})

func (*DevLogger) Warnf

func (log *DevLogger) Warnf(format string, args ...interface{})

type 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
}

Experiment defines a single experiment.

func BuildExperiment

func BuildExperiment(dict map[string]interface{}) *Experiment

BuildExperiment creates an Experiment value from a JSON object represented as a Go map.

func NewExperiment

func NewExperiment(key string) *Experiment

NewExperiment creates an experiment with default settings: active, but all other fields empty.

func ParseExperiment

func ParseExperiment(data []byte) *Experiment

ParseExperiment creates an Experiment value from raw JSON input.

func (*Experiment) WithActive

func (exp *Experiment) WithActive(active bool) *Experiment

WithActive sets the enabled flag for an experiment.

func (*Experiment) WithCondition

func (exp *Experiment) WithCondition(condition Condition) *Experiment

WithCondition sets the condition for an experiment.

func (*Experiment) WithCoverage

func (exp *Experiment) WithCoverage(coverage float64) *Experiment

WithCoverage sets the coverage for an experiment.

func (*Experiment) WithFilters

func (exp *Experiment) WithFilters(filters ...Filter) *Experiment

WithFilters sets the filters for an experiment.

func (*Experiment) WithForce

func (exp *Experiment) WithForce(force int) *Experiment

WithForce sets the forced value index for an experiment.

func (*Experiment) WithGroups

func (exp *Experiment) WithGroups(groups ...string) *Experiment

WithGroups sets the groups for an experiment.

func (*Experiment) WithHashAttribute

func (exp *Experiment) WithHashAttribute(hashAttribute string) *Experiment

WithHashAttribute sets the hash attribute for an experiment.

func (*Experiment) WithHashVersion

func (exp *Experiment) WithHashVersion(hashVersion int) *Experiment

WithHashVersion sets the hash version for an experiment.

func (*Experiment) WithIncludeFunction

func (exp *Experiment) WithIncludeFunction(include func() bool) *Experiment

WithInclude sets the inclusion function for an experiment.

func (*Experiment) WithMeta

func (exp *Experiment) WithMeta(meta ...VariationMeta) *Experiment

WithMeta sets the meta information for an experiment.

func (*Experiment) WithName

func (exp *Experiment) WithName(name string) *Experiment

WithName sets the name for an experiment.

func (*Experiment) WithNamespace

func (exp *Experiment) WithNamespace(namespace *Namespace) *Experiment

WithNamespace sets the namespace for an experiment.

func (*Experiment) WithPhase

func (exp *Experiment) WithPhase(phase string) *Experiment

WithPhase sets the phase for an experiment.

func (*Experiment) WithRanges

func (exp *Experiment) WithRanges(ranges ...Range) *Experiment

WithRanges set the ranges for an experiment.

func (*Experiment) WithSeed

func (exp *Experiment) WithSeed(seed string) *Experiment

WithSeed sets the hash seed for an experiment.

func (*Experiment) WithStatus

func (exp *Experiment) WithStatus(status ExperimentStatus) *Experiment

WithStatus sets the status for an experiment.

func (*Experiment) WithURL

func (exp *Experiment) WithURL(url *regexp.Regexp) *Experiment

WithURL sets the URL for an experiment.

func (*Experiment) WithVariations

func (exp *Experiment) WithVariations(variations ...FeatureValue) *Experiment

WithVariations set the feature variations for an experiment.

func (*Experiment) WithWeights

func (exp *Experiment) WithWeights(weights ...float64) *Experiment

WithWeights set the weights for an experiment.

type ExperimentCallback

type ExperimentCallback func(experiment *Experiment, result *Result)

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 ExperimentOverride

type ExperimentOverride struct {
	Condition Condition
	Weights   []float64
	Active    *bool
	Status    *ExperimentStatus
	Force     *int
	Coverage  *float64
	Groups    []string
	Namespace *Namespace
	URL       *regexp.Regexp
}

ExperimentOverride provides the possibility to temporarily override some experiment settings.

type ExperimentOverrides

type ExperimentOverrides map[string]*ExperimentOverride

type ExperimentStatus

type ExperimentStatus string
const (
	DraftStatus   ExperimentStatus = "draft"
	RunningStatus ExperimentStatus = "running"
	StoppedStatus ExperimentStatus = "stopped"
)

type Feature

type Feature struct {
	DefaultValue FeatureValue   `json:"defaultValue"`
	Rules        []*FeatureRule `json:"rules"`
}

Feature has a default value plus rules than can override the default.

func BuildFeature

func BuildFeature(val interface{}) *Feature

BuildFeature creates a Feature value from a generic JSON value.

func ParseFeature

func ParseFeature(data []byte) *Feature

ParseFeature creates a single Feature value from raw JSON input.

type FeatureAPIResponse

type FeatureAPIResponse struct {
	Status            int                 `json:"status"`
	Features          map[string]*Feature `json:"features"`
	DateUpdated       time.Time           `json:"dateUpdated"`
	EncryptedFeatures string              `json:"encryptedFeatures"`
}

func BuildFeatureAPIResponse

func BuildFeatureAPIResponse(dict map[string]interface{}) *FeatureAPIResponse

BuildFeatureAPIResponse creates a FeatureAPIResponse value from a generic JSON value.

func ParseFeatureAPIResponse

func ParseFeatureAPIResponse(data []byte) *FeatureAPIResponse

ParseFeature creates a single Feature value from raw JSON input.

func (*FeatureAPIResponse) MarshalJSON

func (r *FeatureAPIResponse) MarshalJSON() ([]byte, error)

func (*FeatureAPIResponse) UnmarshalJSON

func (r *FeatureAPIResponse) UnmarshalJSON(data []byte) error

type FeatureMap

type FeatureMap map[string]*Feature

FeatureMap is a map of feature objects, keyed by string feature IDs.

func BuildFeatureMap

func BuildFeatureMap(dict map[string]interface{}) FeatureMap

BuildFeatureMap creates a FeatureMap value from a JSON object represented as a Go map.

func ParseFeatureMap

func ParseFeatureMap(data []byte) FeatureMap

ParseFeatureMap creates a FeatureMap value from raw JSON input.

type FeatureRepoOptions

type FeatureRepoOptions struct {
	AutoRefresh bool
	Timeout     time.Duration
	SkipCache   bool
}

type FeatureResult

type FeatureResult struct {
	Value            FeatureValue
	Source           FeatureResultSource
	On               bool
	Off              bool
	RuleID           string
	Experiment       *Experiment
	ExperimentResult *Result
}

FeatureResult is the result of evaluating a feature.

func BuildFeatureResult

func BuildFeatureResult(dict map[string]interface{}) *FeatureResult

BuildFeatureResult creates an FeatureResult value from a JSON object represented as a Go map.

func (*FeatureResult) GetValueWithDefault

func (fr *FeatureResult) GetValueWithDefault(def FeatureValue) FeatureValue

GetValueWithDefault extracts a value from a FeatureResult with a default.

type FeatureResultSource

type FeatureResultSource uint

FeatureResultSource is an enumerated type representing the source of a FeatureResult.

const (
	UnknownResultSource FeatureResultSource = iota + 1
	DefaultValueResultSource
	ForceResultSource
	ExperimentResultSource
	OverrideResultSource
)

FeatureResultSource values.

func ParseFeatureResultSource

func ParseFeatureResultSource(source string) FeatureResultSource

ParseFeatureResultSource creates a FeatureResultSource value from its string representation.

type FeatureRule

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
}

FeatureRule overrides the default value of a Feature.

func BuildFeatureRule

func BuildFeatureRule(val interface{}) *FeatureRule

BuildFeatureRule creates an FeatureRule value from a generic JSON value.

type FeatureUsageCallback

type FeatureUsageCallback func(key string, result *FeatureResult)

FeatureUsageCallback is a callback function that is executed every time a feature is evaluated.

type FeatureValue

type FeatureValue interface{}

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{}.

func BuildFeatureValues

func BuildFeatureValues(val interface{}) []FeatureValue

BuildFeatureValues creates a FeatureValue array from a generic JSON value.

type Filter

type Filter struct {
	Attribute   string
	Seed        string
	HashVersion int
	Ranges      []Range
}

Filter represents a filter condition for experiment mutual exclusion.

type ForcedVariationsMap

type ForcedVariationsMap map[string]int

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 GrowthBook

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

GrowthBook is the main export of the SDK.

func New

func New(context *Context) *GrowthBook

New creates a new GrowthBook instance.

func (*GrowthBook) Attributes

func (gb *GrowthBook) Attributes() Attributes

Attributes returns the attributes in a GrowthBook's context, possibly modified by overrides.

func (*GrowthBook) ClearSavedResults

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 (*GrowthBook) ClearTrackingData

func (gb *GrowthBook) ClearTrackingData()

ClearTrackingData clears out records of calls to the experiment tracking callback.

func (*GrowthBook) EvalFeature

func (gb *GrowthBook) EvalFeature(id string) *FeatureResult

EvalFeature returns the result for a feature identified by a string feature key.

func (*GrowthBook) Feature deprecated

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 (*GrowthBook) Features

func (gb *GrowthBook) Features() FeatureMap

Features returns the features in a GrowthBook's context.

func (*GrowthBook) ForceVariation

func (gb *GrowthBook) ForceVariation(key string, variation int)

func (*GrowthBook) GetAPIInfo

func (gb *GrowthBook) GetAPIInfo() (string, string)

GetAPIInfo gets the hostname and client key for GrowthBook API access.

func (*GrowthBook) GetAllResults

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 (*GrowthBook) GetFeatureValue

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 (*GrowthBook) IsOff

func (gb *GrowthBook) IsOff(key string) bool

IsOff determines whether a feature is off.

func (*GrowthBook) IsOn

func (gb *GrowthBook) IsOn(key string) bool

IsOn determines whether a feature is on.

func (*GrowthBook) LatestFeatureUpdate

func (gb *GrowthBook) LatestFeatureUpdate() *time.Time

func (*GrowthBook) LoadFeatures

func (gb *GrowthBook) LoadFeatures(options *FeatureRepoOptions)

func (*GrowthBook) Ready

func (gb *GrowthBook) Ready() bool

Ready returns the ready flag, which indicates that features have been loaded.

func (*GrowthBook) RefreshFeatures

func (gb *GrowthBook) RefreshFeatures(options *FeatureRepoOptions)

func (*GrowthBook) Run

func (gb *GrowthBook) Run(exp *Experiment) *Result

Run an experiment. (Uses doRun to make wrapping for subscriptions simple.)

func (*GrowthBook) Subscribe

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 (*GrowthBook) UnforceVariation

func (gb *GrowthBook) UnforceVariation(key string)

func (*GrowthBook) WithAPIHost

func (gb *GrowthBook) WithAPIHost(host string) *GrowthBook

WithAPIHost sets the API host of a context.

func (*GrowthBook) WithAttributeOverrides

func (gb *GrowthBook) WithAttributeOverrides(overrides Attributes) *GrowthBook

WithAttributeOverrides updates the current attribute overrides.

func (*GrowthBook) WithAttributes

func (gb *GrowthBook) WithAttributes(attrs Attributes) *GrowthBook

WithAttributes updates the attributes in a GrowthBook's context.

func (*GrowthBook) WithClientKey

func (gb *GrowthBook) WithClientKey(key string) *GrowthBook

WithClientKey sets the API client key of a context.

func (*GrowthBook) WithDecryptionKey

func (gb *GrowthBook) WithDecryptionKey(key string) *GrowthBook

WithDecryptionKey sets the decryption key of a context.

func (*GrowthBook) WithDevMode

func (gb *GrowthBook) WithDevMode(devMode bool) *GrowthBook

WithDevMode can be used to enable or disable the development mode for a context.

func (*GrowthBook) WithEnabled

func (gb *GrowthBook) WithEnabled(enabled bool) *GrowthBook

WithEnabled sets the enabled flag in a GrowthBook's context.

func (*GrowthBook) WithEncryptedFeatures

func (gb *GrowthBook) WithEncryptedFeatures(encrypted string, key string) (*GrowthBook, error)

WithEncryptedFeatures updates the features in a GrowthBook's context from encrypted data.

func (*GrowthBook) WithFeatureUsageCallback

func (gb *GrowthBook) WithFeatureUsageCallback(callback FeatureUsageCallback) *GrowthBook

WithFeatureUsageCallback is used to set a feature usage callback for a context.

func (*GrowthBook) WithFeatures

func (gb *GrowthBook) WithFeatures(features FeatureMap) *GrowthBook

WithFeatures updates the features in a GrowthBook's context.

func (*GrowthBook) WithForcedFeatures

func (gb *GrowthBook) WithForcedFeatures(values map[string]interface{}) *GrowthBook

WithForcedFeatures updates the current forced feature values.

func (*GrowthBook) WithForcedVariations

func (gb *GrowthBook) WithForcedVariations(forcedVariations ForcedVariationsMap) *GrowthBook

WithForcedVariations sets the forced variations in a GrowthBook's context.

func (*GrowthBook) WithGroups

func (gb *GrowthBook) WithGroups(groups map[string]bool) *GrowthBook

WithGroups sets the groups map of a context.

func (*GrowthBook) WithQAMode

func (gb *GrowthBook) WithQAMode(qaMode bool) *GrowthBook

WithQAMode can be used to enable or disable the QA mode for a context.

func (*GrowthBook) WithTrackingCallback

func (gb *GrowthBook) WithTrackingCallback(callback ExperimentCallback) *GrowthBook

WithTrackingCallback is used to set a tracking callback for a context.

func (*GrowthBook) WithURL

func (gb *GrowthBook) WithURL(url *url.URL) *GrowthBook

WithURL sets the URL in a GrowthBook's context.

type Logger

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{})
}

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 Namespace

type Namespace struct {
	ID    string
	Start float64
	End   float64
}

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.

func BuildNamespace

func BuildNamespace(val interface{}) *Namespace

BuildNamespace creates a Namespace value from a generic JSON value.

func ParseNamespace

func ParseNamespace(data []byte) *Namespace

ParseNamespace creates a Namespace value from raw JSON input.

type Range

type Range struct {
	Min float64
	Max float64
}

Range represents a single bucket range.

func (*Range) InRange

func (r *Range) InRange(n float64) bool

type RepositoryKey

type RepositoryKey string

type Result

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
}

Result records the result of running an Experiment given a specific Context.

func BuildResult

func BuildResult(dict map[string]interface{}) *Result

BuildResult creates an Result value from a JSON object represented as a Go map.

type URLTarget

type URLTarget struct {
	Type    URLTargetType
	Include bool
	Pattern string
}

URL match target.

type URLTargetType

type URLTargetType uint

URL matching supports regular expressions or simple string matches.

const (
	RegexURLTarget  URLTargetType = iota
	SimpleURLTarget               = iota
)

type VariationMeta

type VariationMeta struct {
	Passthrough bool
	Key         string
	Name        string
}

VariationMeta represents meta-information that can be passed through to tracking callbacks.

Jump to

Keyboard shortcuts

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