growthbook

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2023 License: MIT Imports: 9 Imported by: 6

README

GrowthBook Go SDK

Requirements

  • Go version 1.17 or higher

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

View Source
const (
	ErrJSONFailedToParse       = "failed parsing JSON input"
	ErrJSONInvalidType         = "invalid JSON data type"
	ErrCtxJSONInvalidURL       = "invalid URL in JSON context data"
	ErrCtxArrayInAttributes    = "array values not permitted in attributes (use a slice)"
	ErrExpJSONInvalidCondition = "invalid condition in JSON experiment data"
	ErrCondJSONNot             = "invalid $not in JSON condition data"
	ErrCondJSONSequence        = "something wrong in condition sequence"
	ErrCondJSONSequenceElement = "something wrong in condition sequence element"

	WarnJSONUnknownKey            = "unknown key in JSON data"
	WarnCondCompareTypeMismatch   = "types don't match in condition comparison operation"
	WarnExpJSONKeyNotSet          = "key not set in JSON experiment data"
	WarnExpCoverageMustBePositive = "Experiment coverage must be greater than or equal to 0"
	WarnExpCoverageMustBeFraction = "Experiment coverage must be less than or equal to 1"
	WarnExpWeightsWrongLength     = "Experiment weights and variations arrays must be the same length"
	WarnExpWeightsWrongTotal      = "Experiment weights must add up to 1"
	WarnRuleSkipHashAttributeType = "Skip rule because of non-string hash attribute"

	InfoRuleSkipCondition          = "Skip rule because of condition"
	InfoRuleSkipNoHashAttribute    = "Skip rule because of missing hash attribute"
	InfoRuleSkipEmptyHashAttribute = "Skip rule because of empty hash attribute"
	InfoRuleSkipCoverage           = "Skip rule because of coverage"
	InfoRuleSkipUserNotInExp       = "Skip rule because user not in experiment"
)

Message constants used for logging.

Variables

This section is empty.

Functions

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 Attributes

type Attributes map[string]interface{}

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

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
	Valid            bool
	Attributes       Attributes
	URL              *url.URL
	Features         FeatureMap
	ForcedVariations ForcedVariationsMap
	QAMode           bool
	TrackingCallback ExperimentCallback
}

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

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

WithAttributes sets the attributes for a context.

func (*Context) WithEnabled

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

WithEnabled sets the enabled flag 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) 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(trackingCallback 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.

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
	Weights       []float64
	Active        bool
	Coverage      *float64
	Condition     Condition
	Namespace     *Namespace
	Force         *int
	HashAttribute *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) WithForce

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

WithForce sets the forced value index for an experiment.

func (*Experiment) WithHashAttribute

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

WithHashAttribute sets the hash attribute for an experiment.

func (*Experiment) WithNamespace

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

WithNamespace sets the namespace 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 *ExperimentResult)

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 ExperimentResult

type ExperimentResult struct {
	InExperiment  bool
	VariationID   int
	Value         FeatureValue
	HashAttribute string
	HashValue     string
}

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

func BuildExperimentResult

func BuildExperimentResult(dict map[string]interface{}) *ExperimentResult

BuildExperimentResult creates an ExperimentResult value from a JSON object represented as a Go map.

type Feature

type Feature struct {
	DefaultValue FeatureValue
	Rules        []*FeatureRule
}

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 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 FeatureResult

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

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 (
	UnknownFeatureResultSource FeatureResultSource = iota + 1
	DefaultValueResultSource
	ForceResultSource
	ExperimentResultSource
)

FeatureResultSource values.

func ParseFeatureResultSource

func ParseFeatureResultSource(source string) FeatureResultSource

ParseFeatureResultSource creates a FeatureResultSource value from its string representation.

type FeatureRule

type FeatureRule struct {
	Condition     Condition
	Coverage      *float64
	Force         FeatureValue
	Variations    []FeatureValue
	TrackingKey   *string
	Weights       []float64
	Namespace     *Namespace
	HashAttribute *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 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 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 created a new GrowthBook instance.

func (*GrowthBook) Attributes

func (gb *GrowthBook) Attributes() Attributes

Attributes returns the attributes from a GrowthBook's context.

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

func (gb *GrowthBook) Enabled() bool

Enabled returns the enabled flag from a GrowthBook's context.

func (*GrowthBook) Feature

func (gb *GrowthBook) Feature(key string) *FeatureResult

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 from a GrowthBook's context.

func (*GrowthBook) ForcedVariations

func (gb *GrowthBook) ForcedVariations() ForcedVariationsMap

ForcedVariations returns the forced variations from a GrowthBook's context.

func (*GrowthBook) GetAllResults

func (gb *GrowthBook) GetAllResults() map[string]*ExperimentResult

GetAllResults returns a map containing all the latest results from all experiments that have been run, indexed by the experiment key.

func (*GrowthBook) Run

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

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

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

URL returns the URL from a GrowthBook's context.

func (*GrowthBook) WithAttributes

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

WithAttributes updates the attributes in a GrowthBook's context.

func (*GrowthBook) WithEnabled

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

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

func (*GrowthBook) WithFeatures

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

WithFeatures update the features in a GrowthBook's context.

func (*GrowthBook) WithForcedVariations

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

WithForcedVariations sets the forced variations in a GrowthBook's 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 VariationRange

type VariationRange struct {
	Min float64
	Max float64
}

VariationRange represents a single bucket range.

Jump to

Keyboard shortcuts

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