Experiment Go SDK

Official documentation for Amplitude Experiment's server-side Go SDK implementation.

This documentation is split into two sections for remote and local evaluation:

Remote evaluation

Implements fetching variants for a user via remote evaluation.

Install

Install the Go Server SDK using go get.

1go get github.com/amplitude/experiment-go-server

Quick start

  1. Initialize the experiment client
  2. Fetch variants for the user
  3. Access a flag's variant
1// (1) Initialize the local evaluation client with a server deployment key.
2client := remote.Initialize("<DEPLOYMENT_KEY>", nil)
3 
4// (2) Fetch variants for a user
5user := &experiment.User{
6 UserId: "user@company.com",
7 DeviceId: "abcdefg",
8 UserProperties: map[string]interface{}{
9 "premium": true,
10 },
11}
12variants, err := client.Fetch(user)
13if err != nil {
14 // Handle error
15}
16 
17// (3) Access a flag's variant
18variant := variants["<FLAG_KEY>"]
19if variant.Value == "on" {
20 // Flag is on
21} else {
22 // Flag is off
23}

Initialize

The SDK client should be initialized in your server on startup. The deployment key argument passed into the apiKey parameter must live within the same project that you are sending analytics events to.

1func Initialize(apiKey string, config *Config) *Client
Parameter Requirement Description
apiKey required The deployment key which authorizes fetch requests and determines which flags should be evaluated for the user.
config optional The client configuration used to customize SDK client behavior.
1client := remote.Initialize("<DEPLOYMENT_KEY>", nil)

Configuration

The SDK client can be configured on initialization.

Name
Description Default Value
Debug Set to true to enable debug logging. false
ServerUrl The host to fetch flag configurations from. https://api.lab.amplitude.com
FlagConfigPollingInterval The timeout for fetching variants in milliseconds. This timeout only applies to the initial request, not subsequent retries 500 * time.Millisecond
RetryBackoff.FetchRetries The number of retries to attempt if a request to fetch variants fails. 1
RetryBackoff.FetchRetryBackoffMin The minimum (initial) backoff after a request to fetch variants fails. This delay is scaled by the RetryBackoff.FetchRetryBackoffScalar 0
RetryBackoff.FetchRetryBackoffMax The maximum backoff between retries. If the scaled backoff becomes greater than the max, the max is used for all subsequent requests 10 * time.Second
RetryBackoff.FetchRetryBackoffScalar Scales the minimum backoff exponentially. 1
RetryBackoff.FetchRetryTimeout The request timeout for retrying variant fetches. 500 * time.Millisecond

EU data center

If you're using Amplitude's EU data center, configure the serverUrl option on initialization to https://api.lab.eu.amplitude.com

Fetch

Fetches variants for a user and returns the results. This function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.

1func (c *Client) Fetch(user *experiment.User) (map[string]experiment.Variant, error)
Parameter Requirement Description
user required The user to remote fetch variants for.
1user := &experiment.User{
2 UserId: "user@company.com",
3 DeviceId: "abcdefg",
4 UserProperties: map[string]interface{}{
5 "premium": true,
6 },
7}
8variants, err := client.Fetch(user)
9if err != nil {
10 // Handle error
11}

After fetching variants for a user, you may to access the variant for a specific flag.

1variant := variants["<FLAG_KEY>"]
2if variant.Value == "on" {
3 // Flag is on
4} else {
5 // Flag is off
6}

Local evaluation

Implements evaluating variants for a user via local evaluation. If you plan on using local evaluation, you should understand the tradeoffs.

Install

Install the Go Server SDK using go get.

1go get github.com/amplitude/experiment-go-server

Quick start

  1. Initialize the local evaluation client.
  2. Start the local evaluation client.
  3. Evaluate a user.
1// (1) Initialize the local evaluation client with a server deployment key.
2client := local.Initialize("<DEPLOYMENT_KEY>", nil)
3 
4// (2) Start the local evaluation client.
5err := client.Start()
6if err != nil {
7 panic(err)
8}
9 
10 // (3) Evaluate a user.
11user := &experiment.User{DeviceId: "abcdefg"}
12variants, err := client.EvaluateV2(user, nil)
13if err != nil {
14 panic(err)
15}

Initialize

Initializes a local evaluation client.

Server deployment key

You must initialize the local evaluation client with a server deployment key to get access to local evaluation flag configs.

1func Initialize(apiKey string, config *Config) *Client
Parameter Requirement Description
apiKey required The server deployment key which authorizes fetch requests and determines which flags should be evaluated for the user.
config optional The client configuration used to customize SDK client behavior.

!!!tip "Flag Polling Interval"

Flag polling interval

Use the FlagConfigPollingInterval configuration to determine the time flag configs take to update once modified (default 30s).

Configuration

The SDK client can be configured on initialization.

Config

Name
Description Default Value
Debug Set to true to enable debug logging. false
ServerUrl The host to fetch flag configurations from. https://api.lab.amplitude.com
FlagConfigPollingInterval The interval to poll for updated flag configs after calling Start() 30 * time.Second
FlagConfigPollerRequestTimeout The timeout for the request made by the flag config poller 10 * time.Second
AssignmentConfig Configuration for automatically tracking assignment events after an evaluation. nil

AssignmentConfig

Name
Description Default Value
cacheCapacity The maximum number of assignments stored in the assignment cache 524288
Config Options to configure the underlying Amplitude Analytics SDK used to track assignment events

EU data center

If you're using Amplitude's EU data center, configure the serverUrl option on initialization to https://api.lab.eu.amplitude.com

Start

Start the local evaluation client, pre-fetching local evaluation mode flag configs for evaluation and starting the flag config poller at the configured interval.

1func (c *Client) Start() error

You should await the result of Start() to ensure that flag configs are ready to be used before calling Evaluate()

1err := client.Start()
2if err != nil {
3 panic(err)
4}

Evaluate

Executes the evaluation logic using the flags pre-fetched on Start(). Evaluate must be given a user object argument and can optionally be passed an array of flag keys if only a specific subset of required flag variants are required.

!!!tip "Automatic Assignment Tracking"

Automatic assignment tracking

Set AssignmentConfig to automatically track an assignment event to Amplitude when EvaluateV2() is called.

1func (c *Client) EvaluateV2(user *experiment.User, flagKeys []string) (map[string]experiment.Variant, error)
Parameter Requirement Description
user required The user to evaluate.
flagKeys optional Specific flags or experiments to evaluate. If nil, or empty, all flags and experiments are evaluated.
1// The user to evaluate
2user := &experiment.User{DeviceId: "abcdefg"}
3 
4// Evaluate all flag variants
5allVariants, err := client.EvaluateV2(user, nil)
6if err != nil {
7 // Handle Error
8}
9 
10// Evaluate a specific subset of flag variants
11specificVariants, err := client.EvaluateV2(user, []string{
12 "<FLAG_KEY_1>",
13 "<FLAG_KEY_2>",
14})
15 
16// Access a variant
17variant := allVariants["<FLAG_KEY>"]
18if variant.Value == "on" {
19 // Flag is on
20} else {
21 // Flag is off
22}
Was this page helpful?

Thanks for your feedback!

June 4th, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.