Skip to main content

Go SDK

Introduction

Welcome to the Kameleoon Go SDK documentation. This guide has been designed to assist you with integrating our SDK into your Go applications quickly and easily. By following the steps outlined in this guide, you will be able to activate feature flags and run feature experiments in just a few minutes.

note

Before you begin installing our Go SDK, we recommend that you read our technical considerations article to gain an understanding of the fundamental technological concepts behind our SDKs. This will help you to better understand the SDK and ensure a successful integration.

Requirements

Our Go SDK supports Go version 1.15 or higher.

Changelog

Latest version of the Go SDK: 2.1.0 (changelog).

Installation

Installing the Go client

To install the Kameleoon Go SDK, you can use the go get command and install our package directly from our GitHub repository. Simply run the command below:

go get github.com/Kameleoon/client-go/v2

Additional configuration

To provide additional settings for the Go SDK, you can use a configuration file, which allows you to customize the SDK's behavior. You can download a sample configuration file from here.

We recommend installing this file to the default path of /etc/kameleoon/client-go.yaml, which will be read automatically. If you need to customize this, you can provide an additional argument to the NewClient() method. You can either specify a string that indicates an alternative path to the configuration file or directly add a JavaScript object (map) containing the configuration.

The current version of the Go SDK has the following keys available in the configuration file:

KeyDescription
client_idA client_id is required for authentication to the Kameleoon service.
client_secretA client_secret is required for authentication to the Kameleoon service.
site_codeUnique identifier code of the project (website or app), which can be found in our platform's back-office.
actions_configuration_refresh_intervalThis setting specifies the refresh interval, in minutes, for fetching the configuration of experiments and feature flags that are currently active. The value set here determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. If left unspecified, the default interval is set to 60 minutes. Additionally, we offer a streaming mode that utilizes server-sent events (SSE) to allow the SDK to automatically receive and apply new configurations in real-time, without any delays.
proxy_hostThis sets the proxy host for all outgoing server calls made by the SDK.
environmentEnvironment from which a feature flag’s configuration is to be used. The value can be production, staging, development. If no value is specified, the default environment is production. For more information on managing environments, please refer to this article.
note

To learn more about client_id and client_secret, as well as instructions on how to obtain them, please refer to this article. It's worth noting that our Go SDK utilizes the Automation API and follows the OAuth 2.0 client credentials flow.

SDK methods

To configure your Go app and start running feature experiments and deploying new features to your users, please follow the instructions provided in the Main usage section. This section includes all the necessary steps for properly configuring the Kameleoon Go SDK, along with essential development tools.

  1. Initializing the Kameleoon Client
  2. Getting access to feature flags and variations
  3. Tracking goals
note

In addition to using Kameleoon’s Go SDK to roll out new features and define advanced delivery rules with our Feature Management & Experimentation solution, you can also leverage this SDK for running server-side and hybrid experiments (without utilizing feature flags). For more information on configuring these experiments, please refer to the triggerExperiment method.

We highly recommend that you take a look at the Additional Tools section, which includes additional useful information on features and utility hooks that can simplify the usage of the Go SDK:

To run server-side or hybrid experiments, without the need to configure feature flags, use the following methods:

Main usage

Below is a step-by-step guide for configuring the Go SDK in your application and start activating feature flags.

1. Initializing the Kameleoon Client

Once you have installed our SDK in your application, the first step is to initialize Kameleoon. All interactions with the SDK, such as triggering an experiment, are accomplished via the object (the Kameleoon client) created by using the NewClient() method.

It is possible to customize the behavior of the SDK (e.g., the environment, the credentials...) by providing a configuration object.

import (
kameleoon "github.com/Kameleoon/client-go/v2"
)

/// First option
config := &kameleoon.Config{}
err := config.Load("/etc/kameleoon/client-go.yaml")

// Second option
config := &kameleoon.Config{
Network: kameleoon.NetworkConfig{ // Optional
ProxyURL: "http://proxy-pass:1234/", // Optional
DoTimeout: 10 * time.Second, // Optional
ReadTimeout: 5 * time.Second, // Optional
WriteTimeout: 5 * time.Second, // Optional
MaxConnsPerHost: 10000, // Optional
},
SiteCode: "your-project-sitecode", // This field is required. Please enter your project's sitecode here.
ClientID: "your-client-id", // This field is required. Please enter your client_id here.
ClientSecret: "your-client-secret", // This field is required. Please enter your client_secret here.
ConfigUpdateInterval: time.Hour, // Optional
Environment: "staging", // Optional
VisitorDataMaxSize: 500, //eg. 500mb
}

// create a client, config - mandatory
client := kameleoon.NewClient(config)
Arguments
NameTypeDescription
cfgConfigThis field is mandatory and should either represent the path to the SDK configuration file or the configuration object directly, which must contain the correct configuration keys.
Return value
TypeDescription
ClientAn instance of the Client class, that will be used to manage your experiments and feature flags.

RunWhenReady

The initialization of the Kameleoon Client is not immediate, as it requires a server request to our CDN (Content Delivery Network) to retrieve the current configuration for all active experiments and feature flags.

To address this, the RunWhenReady() method of the kameleoon.Client class is available. This method allows you to pass a callback that will execute as soon as the SDK is ready for use.

client.RunWhenReady(func(c *kameleoon.Client, err error) {
if err != nil {
// client wasn't initialized
fmt.Println(err)
}
// The SDK has been initialized, you can fetch a feature flag / experiment configuration here.
})
Arguments
NameTypeDescription
callbackfunc(c *kameleoon.Client, err error)Callback object. This field is mandatory.

2. Getting access to feature flags and variations

note

To implement a feature flag in your code, you must first create a feature flag in your Kameleoon account.

After the SDK has been initialized, you can obtain a feature flag configuration. Subsequently, all methods will require you to specify the User ID or visitorCode associated with the request.

note

If you are using Kameleoon in Hybrid mode with mixed front-end and back-end environments, you can call the ObtainVisitorCode() helper method to obtain the Kameleoon visitorCode for the current visitor. Alternatively, if you provide your own User ID, you must ensure its uniqueness on your end.

To associate various data points with the current user, you can use the AddData() method. This method requires the visitorCode as the first parameter and accepts several additional parameters. These additional parameters represent the various data types allowed in Kameleoon.

visitorCode, err := client.ObtainVisitorCode(req, resp, "example.com")

// This is required if you want to filter out bots from your traffic. You need to get the user agent for the visitor and pass it to the Kameleoon client object
client.AddData(visitorCode, &types.UserAgent{Value: "visitor_user_agent"})

client.AddData(visitorCode, &types.Browser{Type: types.BrowserTypeChrome})

Feature flags can be very useful for implementing ON/OFF switches with optional but advanced user targeting rules. However, you can also use feature flags to run feature experiments with several variations of your feature flag. Check out our documentation on creating feature experiments for more information.

IsFeatureActive

This method can be used if you want to retrieve the configuration of a simple feature flag, that has only a turn ON / OFF state, as opposed to more complex feature flags with multiple variations or targeting options. If your feature flag has variations and variables, you should use the GetFeatureVariationKey method.

It takes a visitorCode and featureKey as mandatory arguments to check if the feature flag is active for a given user.

If the user has not been associated with your feature flag before, the SDK returns a random boolean value (true if the user should have this feature or false if not). However, if the user has already been registered with this feature flag, the SDK detects the previous feature flag value.

note

It is important to set up proper error handling in your code to catch any potential exceptions that may occur, as shown in the code example.

featureKey := "new_checkout";

// Check if a Feature Flag is active (ON / OFF)
hasNewCheckout, err := client.IsFeatureActive(visitorCode, featureKey)
if err != nil {
switch err.(type) {
case *kameleoon.ErrVisitorCodeNotValid:
// The provided visitor code is not valid. Trigger the old checkout for this visitor.
hasNewCheckout = false
case *kameleoon.ErrFeatureConfigNotFound:
// The Feature Key is not yet in the configuration file that has been fetched by the SDK. Trigger the old checkout for this visitor.
hasNewCheckout = false
default:
// Handle unexpected errors
panic(err)
}
}
if hasNewCheckout {
// Implement new checkout code here
}
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
featureKeystringThe key of the feature you want to expose to a user. This field is mandatory.
Return value
TypeDescription
boolValue of the feature flag that is registered for a given visitorCode.
Exceptions Thrown
TypeDescription
kameleoon.ErrFeatureConfigNotFoundThis exception indicates that the requested feature key could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode.
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

GetFeatureVariationKey

This method retrieves the configuration of a feature experiment with several feature variations. You can use it to get a variation key for a given user by providing the visitorCode and featureKey as mandatory arguments.

If the user has never been associated with the feature flag, the SDK returns a variation key randomly, following the feature flag rules. If the user is already registered with the feature flag, the SDK detects the previous variation key value. If the user doesn't match any of the rules, the default value defined in Kameleoon's feature flag delivery rules will be returned. It's important to note that the default value may not be a variation key, but a boolean value or another data type, depending on the feature flag configuration.

note

Don't forget to handle potential exceptions with proper error handling in your code. Check out the example code for guidance.

// Feature Experiment with variations
variationKey = ""

if variationKey, err := s.client.GetFeatureVariationKey(visitorCode, featureKey); err == nil {
switch variationKey {
case "variation 1":
// The visitor has been bucketed with variation 1 key
case "variation 2":
// The visitor has been bucketed with variation 2 key
default:
//The visitor has been bucketed with the default variation or is part of the unallocated traffic sample
}
} else {
// An error occurred, the feature flag key has not been found in the current configuration fetched by the SDK
}
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
featureKeystringThe key of the feature you want to expose to a user. This field is mandatory.
Return value
TypeDescription
stringVariation key of the feature flag that is registered for a given visitorCode.
Exceptions Thrown
TypeDescription
kameleoon.ErrFeatureConfigNotFoundThis exception indicates that the requested feature key could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode.
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

3. Tracking goals

TrackConversion

This method is used to track conversions for any goal that has been set up in your Kameleoon account. To use this method, you must provide the visitorCode and goalID as mandatory arguments to track the conversion for a particular goal.

The trackConversion() method should be called when the user has completed the action that you are tracking as a conversion. For example, if you are tracking purchases, you would call trackConversion() when the user has completed the checkout process.

Additionally, you can pass a third argument revenue to the TrackConversionRevenue() method to track the revenue generated by the conversion.

Both methods don't return any value and are non-blocking as the server call is made asynchronously.


import (
"github.com/Kameleoon/client-go/v2/types"
)

goalID = 83023

client.TrackConversion(visitorCode, goalID)

client.TrackConversionRevenue(visitorCode, goalID, 10.0)
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
goalIdintThe ID of the goal. This field is mandatory.
revenuefloat64The revenue of the conversion. This field is required for the TrackConversionRevenue() method.
Exceptions Thrown
TypeDescription
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

Additional Tools

Obtaining a Visitor Code / Using your own User ID

ObtainVisitorCode

visitorCode, err := client.ObtainVisitorCode(req, resp, "example.com")

visitorCode, err := client.ObtainVisitorCode(req, resp, "example.com", "defaultCode12345")

To ensure user identification consistency, especially when using Kameleoon in Hybrid mode with mixed front-end and back-end environments, you should call the ObtainVisitorCode() helper method to obtain the Kameleoon visitorCode for the current visitor. Here's how it works:

  1. First, Kameleoon checks if there is a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request. If found, it will use this as the visitor identifier.

  2. If no cookie or parameter is found, the method will either randomly generate a new identifier or use the defaultVisitorCode argument if it is passed. Using your own identifiers as visitor codes allows you to match Kameleoon visitors with your own users without additional look-ups in a matching table.

  3. The server-side kameleoonVisitorCode cookie is then set with the identifier value via HTTP header, and the method returns the identifier value.

For more information, please refer to this article.

note

If you decide to provide your own User ID instead of using the Kameleoon generated visitorCode, it is your responsibility to ensure that the User ID is unique. The SDK does not check for uniqueness. It's important to note that the User ID you provide must not exceed 255 characters, as any excess characters will result in an exception being thrown.

Arguments
NameTypeDescription
reqfasthttp.RequestThe current fasthttp.Request object should be passed as the first parameter. This field is mandatory.
respfasthttp.ResponseThe current fasthttp.Response object should be passed as the second parameter. This field is mandatory.
domainstringYour current top level domain for the particular site (this information is necessary to set the corresponding cookie accordingly on the top level domain). This field is mandatory.
defaultVisitorCodestringThis parameter will be used as the visitorCode if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and by default a random visitorCode will be generated.
Return value
TypeDescription
stringA visitorCode that will be associated with this particular user. It should be used with most methods of the SDK.
Exceptions Thrown
Error MessageDescription
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

Getting Feature Variables

GetFeatureVariable

To get a feature variable of a variation key associated with a user, call the GetFeatureVariable() method of our SDK.

This method takes a visitorCode, featureKey and variableKey as mandatory arguments to get a variable of the variation key for a given user.

If the user has never been associated with the feature flag, the SDK returns a variable value of the variation key randomly, following the feature flag rules. If the user is already registered with the feature flag, the SDK detects the previous variation key value and return the variable value. If the user doesn't match any of the rules, the default value will be returned.

Don't forget to handle potential exceptions with proper error handling in your code. Check out the example code for guidance.

visitorCode, err := client.ObtainVisitorCode(req, resp, "example.com")
featureKey := "featureKey";
variableKey = "variableKey"

if variableValue, err := s.client.GetFeatureVariable(visitorCode, featureKey, variableKey); err == nil {
// your custom code depending of variableValue
} else {
// An error occurred, the feature flag has not been found in the current configuration fetched by the SDK.
}
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
featureKeystringThe key of the feature you want to expose to a user. This field is mandatory.
variableKeystringThe name of the variable for which you want to get a value. This field is mandatory.
Return value
TypeDescription
interface{}The value of a variable associated with a particular feature flag's variation that has been registered for a specific visitorCode. Possible types: bool, float64, string, map[string]interface{}
Exceptions Thrown
TypeDescription
kameleoon.ErrFeatureConfigNotFoundThis exception indicates that the requested feature key could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode.
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.
kameleoon.ErrVariationNotFoundThis exception indicates that the requested variation ID could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode.
kameleoon.ErrFeatureVariableNotFoundThis exception indicates that the requested variable key has not been found. Check that the variable's key defined in the Kameleoon Platform matches the one in your code.

GetFeatureAllVariables

To retrieve all variables associated with a feature flag, you need to call the GetFeatureAllVariables() method. This method requires you to provide two mandatory arguments: featureKey and variationKey. The method returns the data with the object type, as defined in the Kameleoon Platform.

Don't forget to handle potential exceptions with proper error handling in your code. Check out the example code for guidance.

featureKey := "test_feature_variables"
variationKey := "on"

if allVariables, err := s.client.GetFeatureAllVariables(featureKey, variationKey); err == nil {
// your custom code
} else {
// An error occurred, the feature flag or variation doesn't exist in the client configuration
}
Arguments
NameTypeDescription
featureKeystringThe key of the feature flag you want to obtain. This field is mandatory.
variationKeystringThe key of the variation you want to obtain. This field is mandatory.
Return value
TypeDescription
map[string]interface{}Data associated with this feature flag and variation. Possible values: string, bool, float64 or map[string]interface{} (depending on the type defined in the Kameleoon Platform).
Exceptions Thrown
TypeDescription
kameleoon.ErrFeatureConfigNotFoundThis exception indicates that the requested feature key could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode.
kameleoon.ErrVariationNotFoundThis exception indicates that the requested variation key could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode.

Obtaining a list of Feature Flags

GetFeatureList

To obtain a list of feature flag keys that are currently available for use with the SDK, you need to call the GetFeatureList() method.

arrayFeatureKeys := client.GetFeatureList()
Return value
TypeDescription
[]stringList of feature flag keys

GetActiveFeatureListForVisitor

The GetActiveFeatureListForVisitor() method takes one input parameter, which is the visitorCode. When you call this method with a specific visitorCode, it will return a list of feature flag keys that are currently available for that visitorCode.

Don't forget to handle potential exceptions with proper error handling in your code. Check out the example code for guidance.

arrayFeatureFlagKeys, err := client.GetActiveFeatureListForVisitor(visitorCode)
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
Return value
TypeDescription
[]stringList of feature flag keys which are active for a specific visitorCode
Exceptions Thrown
TypeDescription
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

Adding User Data

AddData

To associate different data points with the current user, you can use the AddData() method. This method requires the visitorCode as its first parameter, and it also accepts several additional parameters. These additional parameters represent the various Data Types that are allowed in Kameleoon.

import (
"github.com/Kameleoon/client-go/v2/types"
)

client.AddData(visitorCode, &types.Browser{Type: types.BrowserTypeChrome})

client.AddData(visitorCode,
&types.PageView{
URL: "https://url.com",
Title: "title",
Referrers: []int{3},
},
&types.Conversion{
GoalID: 32,
Revenue: 10,
Negative: false,
}
)
note

The AddData() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission via the FlushAll() / FlushVisitor() method that is described in the next paragraph. This approach helps reduce the number of server calls made, as the data is typically grouped into a single server call triggered by the execution of FlushAll() / FlushVisitor().

The TriggerExperiment() and TrackConversion() methods also send out any previously associated data, just like the FlushAll() / FlushVisitor() method. The same holds true for GetFeatureVariationKey() and GetFeatureVariable() methods if an experimentation rule is triggered.

Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
dataDataCustom data types, separated by a comma.
Exceptions Thrown
TypeDescription
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.
CustomData

Custom data is one of the most powerful features of the Kameleoon platform. They allow any kind of data to be easily associated with each visitor and used for many different purposes, such as:

  • building advanced targeting segments for A/B tests and personalizations based on this data.
  • filtering of experiment and personalization reports by any value stored in this data.

client.AddData(visitorCode, &types.CustomData{
ID: "11",
Value: "some value",
})

client.AddData(visitorCode,
types.NewCustomData("1", "first value", "second value"))

values := []string{"one value", "second value"}
client.AddData(visitorCode,
types.NewCustomData("1", values...))

NameTypeDescription
IDstringThe Index / ID of the custom data to be stored. This field is mandatory.
Valueinterface{}The value of the custom data to be stored. This field is mandatory.
note

The index or ID of the custom data can be found in your Kameleoon account. It is important to note that this index starts at 0, which means that the first custom data you create for a given site will be assigned 0 as its ID, not 1.

tip

If you need to set multiple values for a custom data, use the method NewCustomData(id string, values ...string). This method enables you to set a list of values for a custom data of type "List of". It is particularly useful if you use the "Is among the values" operator in our segment builder.

Browser

The browser data set stored here can be used to filter experiment and personalization reports by any value associated with it.

client.AddData(visitorCode, &types.Browser{Type: types.BrowserTypeChrome})
NameTypeDescription
TypeBrowserTypeList of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory.
PageView

The pageview data set stored here can be used to filter experiment and personalization reports by any value associated with it.

client.AddData( visitorCode,
&types.PageView{
URL: "https://url.com",
Title: "title",
Referrers: []int{3},
})
NameTypeDescription
URLstringThe URL of the page viewed. This field is mandatory.
TitlestringThe title of the page viewed. This field is mandatory.
Referrers[]intThe referrers of the viewed pages. This field is optional.
note

The index or ID of the referrer can be found in your Kameleoon account. It is important to note that this index starts at 0, which means that the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.

Conversion

The Conversion data set stored here can be used to filter experiment and personalization reports by any goal associated with it.

client.AddData( visitorCode,
&types.Conversion{
GoalID: 32,
Revenue: 10,
Negative: false,
})
NameTypeDescription
GoalIDintThe ID of the goal. This field is mandatory.
Revenuefloat64Conversion revenue. This field is optional.
NegativeboolDefines if the revenue is positive or negative. This field is optional.
Device

The device data set stored here can be used to filter experiment and personalization reports by any value associated with it.

client.AddData(visitorCode, &types.Device{Type: types.DeviceTypeDesktop})
NameTypeDescription
TypeDeviceTypeList of devices: Phone, Tablet, Desktop. This field is mandatory.
UserAgent
caution

Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. We recommend that you pass the user agent to be filtered by Kameleoon when running server-side experiments for each visitor browsing your website, to avoid counting bots in your analytics.

If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.

tip

If you run a Kameleoon hybrid experiment, your server-side experiments will be automatically protected against bot traffic. This is because Kameleoon collects the user-agent automatically on the front-end side. Therefore, you don't need to pass the user-agent or any other parameter to filter bots and spiders.

client.AddData(visitorCode, &types.UserAgent{Value: "visitor_user_agent"})
NameTypeDescription
ValuestringThe User-Agent value that will be sent with tracking requests. This field is mandatory.

Retrieving data from a remote source

GetRemoteData

The GetRemoteData() method retrieves external data stored on Kameleoon's remote server for the specified siteCode (specified in Client constructor) according to a key passed as an argument. This key is typically the Kameleoon Visitor Code or your own User ID.

For example, you can use this method to retrieve user preferences, historical data, or any other data relevant to your application's logic. By storing this data on our highly scalable servers using our Data API, you can efficiently manage massive amounts of data and retrieve it for each of your visitors or users.

The return value of the method is a JSON object that can be decoded using the json.Unmarshal() function. You can use this data to build advanced targeting segments for feature flags and experiments, or filter experiment and personalization reports based on any value stored in the retrieved data.

type Test1 struct {
Value string `json:"some field to insert or update"`
}

remoteData, err := s.client.GetRemoteData("USER_ID") //use default timeout
var test1 Test1
err = json.Unmarshal(remoteData, &test1)

remoteData, err := s.client.GetRemoteData("USER_ID", 1000)
note

Note that, since a server call is required, this mechanism is asynchronous.

Arguments
NameTypeDescription
keystringThe key with which the data you are trying to retrieve is associated. This field is mandatory. This key is typically the Kameleoon Visitor Code or your own User ID.
timeoutintThe timeout parameter specifies the maximum amount of time the method can block to wait for a result, in milliseconds. This field is optional; if not provided, the method will use the default timeout value provided when initializing the SDK
Return value
TypeDescription
[]byteThis returns the information associated with retrieving data for a specific key. The result needs to be decoded using the json.Unmarshal() function.
Exceptions Thrown
TypeDescription
errorError indicating that the request timed out.
note

We offer built-in integrations with Mixpanel, Segment, and GA4 to fetch external cohorts and utilize them in feature experiments. The key utilized in these integrations is either our own Visitor code or your User ID. You can refer to the sample code provided below to retrieve and utilize Mixpanel cohorts:

//Retrieve and use Mixpanel Cohorts
type Cohort struct {
Id string `json:"mixpanel_cohort_id"`
Name string `json:"mixpanel_cohort_name"`
ProjectId string `json:"mixpanel_cohort_project_id"`
}

type MixPanelCohorts struct {
Cohorts []Cohort `json:"mixpanel_cohorts"`
}

remoteData, _ := s.client.GetRemoteData("USER_ID")
var mixPanel MixPanelCohorts
if err = json.Unmarshal(remoteData, &mixPanel); err == nil {
cohorts := make([]string, len(mixPanel.Cohorts))
for _, cohort := range mixPanel.Cohorts {
cohorts = append(cohorts, cohort.Id)
}
client.AddData(visitorCode,
types.NewCustomData("<CustomData Index>", cohorts...))
}

FlushAll / FlushVisitor

When you associate data with the current user using the AddData() method, it is not immediately sent to our servers. Instead, it is stored and accumulated until it is sent automatically by the TriggerExperiment(), TrackConversion(), GetFeatureVariationKey() and GetFeatureVariable() methods, or manually by the FlushAll() / FlushVisitor() methods. This gives you control over when the data is sent to our servers.

note

It's important to note that the FlushAll() / FlushVisitor() method is non-blocking, meaning that the server call is made asynchronously and does not return any value.


import (
"github.com/Kameleoon/client-go/v2/types"
)

visitorCode, err := client.ObtainVisitorCode(req, resp, "example.com")

client.AddData(visitorCode, &types.Browser{Type: types.BrowserTypeChrome})

client.AddData(visitorCode, &types.Conversion{
GoalID: 32,
Revenue: 10,
Negative: false,
})

client.FlushVisitor(visitorCode)

client.FlushAll()
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory for FlushVisitor()
Exceptions Thrown
TypeDescription
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

Triggering an Experiment (without feature flags)

TriggerExperiment

The TriggerExperiment() method allows you to run server-side or hybrid experiments without the need to configure feature flags. You can use this method to obtain a variation for a given user by passing the visitorCode and experimentID as mandatory arguments.

experimentID := 75253
variationID, err := client.TriggerExperiment(visitorCode, experimentID)
if err != nil {
switch err.(type) {
case *kameleoon.ErrNotTargeted:
// The user did not trigger the experiment, as the associated targeting segment
// conditions were not fulfilled. He should see the reference variation
variationID = 0
case *kameleoon.ErrNotAllocated:
// The user triggered the experiment, but got into unallocated traffic.
// Usually, this happens because the user has been associated with excluded traffic
variationID = 0
case *kameleoon.ErrExperimentConfigNotFound:
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0
default:
// Handle unexpected errors
panic(err)
}
}

If a user has not been associated with any variation before, the SDK will randomly select a variation and return it. However, if a user with a specific visitorCode has already been registered with a variation, the SDK will detect the variation that was previously registered and return its variationID.

Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
experimentIDintThe ID of the experiment you want to trigger for a user. This field is mandatory.
Return value
NameTypeDescription
variationIDintThe ID of the variation that is assigned to a particular visitorCode. The reference or original variation is always assigned an ID of 0 as a convention.
Exceptions Thrown
TypeDescription
kameleoon.ErrExperimentConfigNotFoundThis exception indicates that the requested experiment could not be found in the internal configuration of the SDK. This typically occurs when the experiment has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode.
kameleoon.ErrNotTargetedIndicates that the current visitor or user does not meet the targeting conditions required to participate in a particular experiment. These targeting conditions are defined using Kameleoon's segment builder, which allows you to specify various criteria that must be met in order for a user to be eligible to participate in the experiment. If a user does not meet these conditions, they will be excluded from the experiment and this exception will be raised.
kameleoon.ErrNotAllocatedThis exception is thrown when the current visitor/user met the targeting conditions for the experiment but did not activate it. The reason for this could be that a portion of traffic has been excluded from the experiment and should not be tracked, or there could be other specific criteria that were not met.
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

Getting Variation Associated Data (JSON)

GetVariationAssociatedData

To retrieve the JSON data associated with a variation in Kameleoon's SDK, use the GetVariationAssociatedData() method. This data typically contains metadata about the variation, and can be set up in Kameleoon's web application.

To use the method, provide the variationID as a parameter. The method will return the data as a []byte instance. If the variation ID is incorrect or corresponds to an experiment that is not yet online, an exception (kameleoon.ErrVariationNotFound) will be thrown.

visitorCode := client.ObtainVisitorCode(req, resp, "example.com")

experimentID = 75253
variationID, err = client.TriggerExperiment(visitorCode, experimentID)
if err != nil {
// Handle errors
panic(err)
}

// Raw byte slice response (json)
bytes, err := client.GetVariationAssociatedData(variationID)
if err != nil {
switch err.(type) {
case *kameleoon.ErrVariationNotFound:
// The variation is not yet activated on Kameleoon's side,
// ie the associated experiment is not online
default:
// Handle unexpected errors
panic(err)
}
}
data := make(map[string]string)
if err = json.Unmarshal(bytes, &data); err != nil {
// Handle errors
panic(err)
}

Arguments
NameTypeDescription
variationIdintThe ID of the variation for which you want to obtain the associated data. This field is mandatory.
Return value
TypeDescription
[]byteData associated with this variationID.
Exceptions Thrown
TypeDescription
kameleoon.ErrVariationNotFoundException indicating that the requested variation ID has not been found in the internal configuration of the SDK. This means that the experiment has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode.

Obtaining a list of Experiments

GetExperimentList

This method returns a list of experiment IDs that are currently available for a specific visitorCode, based on the onlyAllocated option.

To use this method, you need to pass two input parameters: visitorCode and onlyAllocated. If the onlyAllocated parameter is set to true, the result will only include experiments where the given visitor has been allocated to. If it's set to false, it will include all experiments that have been targeted to the specific visitorCode, regardless of whether they have been allocated to the experiment or not.

// returns the ids of all targeted experiments for a given visitor
arrayExperimentIds, err := client.GetExperimentListForVisitor(visitorCode, false)

// returns ids of all targeted and simultaneously allocated experiments for a given visitor
arrayExperimentIds, err := client.GetExperimentListForVisitor(visitorCode, true)
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
onlyAllocatedboolIf true, the result only contains experiments where a given visitor got into allocated traffic. Set the value to false to fetch all targeted experiments. This field is mandatory.
Return value
TypeDescription
[]intThe list of experiment IDs available for specific visitorCode according to the onlyAllocated option
Exceptions Thrown
TypeDescription
kameleoon.ErrVisitorCodeNotValidThis exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

Configuration's Real-time Update Events

OnUpdateConfiguration

kameleoonClient.OnUpdateConfiguration(
// configuration was updated
)

The OnUpdateConfiguration() method enables you to manage an event that occurs when there is an updated datafile configuration. This method takes a single input parameter: a function known as the handler. The handler that gets executed automatically whenever the configuration is updated through a real-time configuration event.

Arguments
NameTypeDescription
handlerfunc()The handler that will be called when the configuration is updated using a real-time configuration event.

Sending exposure events to external tools

Kameleoon offers built-in integrations with various analytics and CDP solutions, such as Mixpanel, GA4, Segment.... To ensure that you can track and analyze your server-side experiments, Kameleoon provides a method GetEngineTrackingCode() that returns the JavasScript code to be inserted in your page to send automatically the exposure events to the analytics solution you are using. For more information about hybrid experimentation, please refer to this documentation.

note

To benefit from this feature, you will need to implement both the GO SDK and our Kameleoon JavaScript tag. We recommend you implement the Kameleoon Asynchronous tag, which you can install before your closing <body> tag in your HTML page, as it will be only used for tracking purposes.

GetEngineTrackingCode

engineTrackingCode := kameleoonClient.GetEngineTrackingCode(visitorCode)
// Example of JS code that can be returned:
//
// window.kameleoonQueue = window.kameleoonQueue || [];
// window.kameleoonQueue.push(['Experiments.assignVariation', experiment1ID, variation1ID]);
// window.kameleoonQueue.push(['Experiments.trigger', experiment1ID, true]);
// window.kameleoonQueue.push(['Experiments.assignVariation', experiment2ID, variation2ID]);
// window.kameleoonQueue.push(['Experiments.trigger', experiment2ID, true]);
//
// Here, experiment1ID, experiment2ID and variation1ID, variation2ID represent
// the specific experiments and variations that the specified user has been assigned to
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
Return value
TypeDescription
stringJavasScript code to be inserted in your page