Skip to main content

Go SDK

Welcome to the Kameleoon Go SDK documentation. Follow this guide to integrate the Go 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.18 or higher.

Changelog

Latest version of the Go SDK: 3.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/v3

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.
top_level_domainThe current top-level domain for your website . Use the format: example.com. Don’t include https://, www, or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain. This field is mandatory.
session_durationSets the time interval that Kameleoon stores the visitor and their associated data in memory (RAM). Note that increasing the session duration increases the amount of RAM that needs to be allocated to store visitor data. The default session duration is 30 minutes.
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.
default_timeoutSpecifies the timeout for network requests from the SDK that are not overriden by method-specific timeouts. The default value is 10 seconds. Set the value to 30 seconds or more if you do not have a stable connection. Some methods have additional parameters for method-specific timeouts, but if you do not specify them explicitly, this default value is used.
verbose_modeBoolean value (true or false) that turns on additional logging, including network requests and debug information.
proxy_urlThis 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

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:

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/v3"
)

// First option
config := &kameleoon.KameleoonClientConfig{
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
},
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.
TopLevelDomain: "example.com", // This field is strictly recommended, otherwise you may have problems when using subdomains.
RefreshInterval: time.Hour, // Optional (60 minutes by default)
Environment: "staging", // Optional
SessionDuration: 30 * time.Minute, // Optional (30 minutes by default)
}
client, err := KameleoonClientFactory.Create("your-project-sitecode", config)

// Second option
config, err := LoadConfig("/etc/kameleoon/client-go.yaml")
client, err := KameleoonClientFactory.Create("your-project-sitecode", config)
// Notice: in that case the config is loaded every time. In order to load config only once use `CreateFromFile` instead

// Third option
client, err := KameleoonClientFactory.CreateFromFile("your-project-sitecode", "/etc/kameleoon/client-go.yaml")

KameleoonClientFactory

KameleoonClientFactory manages all instances of KameleoonClient within SDK instance.

Create
const siteCode = "sitecode"
config := &kameleoon.KameleoonClientConfig{
// ...
}

client, err := KameleoonClientFactory.Create(siteCode, config)
Arguments
NameTypeDescription
siteCodestringA Kameleoon siteCode. This field is mandatory.
cfg*KameleoonClientConfigRepresents either the path to the SDK configuration file or the configuration object directly. If you provide the configuration object, it must contain the correct configuration keys. This field is mandatory.
Return value
TypeDescription
KameleoonClientAn instance of the KameleoonClient that will be used to manage your experiments and feature flags.
errorAn error occurred in the Create call. The error can be errs.SiteCodeIsEmpty or errs.ConfigCredentialsInvalid.
CreateFromFile
const siteCode = "sitecode"
client, err := KameleoonClientFactory.CreateFromFile(siteCode, "/etc/kameleoon/client-go.yaml")
Arguments
NameTypeDescription
siteCodestringA Kameleoon siteCode. This field is mandatory.
cfgPathstringA path to the config file. The file is loaded if only the KameleoonClientFactory does not store a KameleoonClient instance with the specified siteCode. This field is mandatory.
Return value
TypeDescription
KameleoonClientAn instance of the KameleoonClient that will be used to manage your experiments and feature flags.
errorAn error occurred within Create. The error can be errs.SiteCodeIsEmpty or errs.ConfigCredentialsInvalid.
Forget
const siteCode = "sitecode"
KameleoonClientFactory.Forget(siteCode)

The Forget method removes a KameleoonClient instance from the KameleoonClientFactory with the specified siteCode and frees resources used by the KameleoonClient instance. The KameleoonClient instance must not be used after calling the Forget method.

Arguments
NameTypeDescription
siteCodestringThe siteCode of the KameleoonClient instance to be removed from the KameleoonClientFactory. This field is mandatory.

WaitInit

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 WaitInit method of the kameleoon.KameleoonClient class is available. This method allows you to wait until the KameleoonClient instance is ready for use.

err := client.WaitInit()
if err != nil {
// Client wasn't initialized properly
fmt.Println(err)
} else {
// The SDK has been initialized, you can fetch a feature flag / experiment configuration here.
}
Return value
TypeDescription
errorAn error occurred during the initialization process.

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 GetVisitorCode() 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.GetVisitorCode(req, resp)

// 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.NewUserAgent("visitor_user_agent"))

client.AddData(visitorCode, types.NewBrowser(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.

const 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 *errs.VisitorCodeInvalid:
// The provided visitor code is not valid. Trigger the old checkout for this visitor.
hasNewCheckout = false
case *errs.FeatureConfigNotFound:
// 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
errs.FeatureConfigNotFoundThis error 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.
errs.VisitorCodeInvalidThis error is returned 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
const 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
errs.FeatureConfigNotFoundThis error 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.
errs.VisitorCodeInvalidThis error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.
errs.FeatureEnvironmentDisabledThis error indicates that the feature flag is disabled for the current environment.

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/v3/types"
)

const 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 optional for the TrackConversionRevenue() method.
Exceptions thrown
TypeDescription
errs.VisitorCodeInvalidThis error is returned 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

GetVisitorCode

note

This method was previously named ObtainVisitorCode, which was removed in SDK version 3.0.0.

visitorCode, err := client.GetVisitorCode(req, resp)

visitorCode, err := client.GetVisitorCode(req, resp, "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 GetVisitorCode() 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 associated with the current HTTP request. If found, it will use this as the visitor identifier.

  2. If no cookie 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
request*fasthttp.RequestThe current fasthttp.Request object should be passed as the first parameter. This field is mandatory.
response*fasthttp.ResponseThe current fasthttp.Response object should be passed as the second parameter. 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
(string, error)A pair consisting of a visitorCode that will be associated with this particular user and an error. It should be used with most methods of the SDK.
Exceptions thrown
Error MessageDescription
errs.VisitorCodeInvalidThis error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.

SetLegalConsent

visitorCode, err := kameleoonClient.GetVisitorCode(req, resp)

err := kameleoonClient.SetLegalConsent(visitorCode, true, resp)

You must use this method to specify whether the visitor has given legal consent to use personal data. Setting the legalConsent parameter to false limits the types of data that you can include in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the Consent management policy.

Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is required.
consentboolA boolean value representing the legal consent status. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. This field is required.
response*fasthttp.ResponseThe HTTP response where values in the cookies will be adjusted based on the legal consent status. This field is optional.
Exceptions thrown
TypeDescription
errs.VisitorCodeInvalidThis error is returned 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.GetVisitorCode(req, resp)
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
errs.FeatureConfigNotFoundThis error 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.
errs.VisitorCodeInvalidThis error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters.
errs.FeatureVariationNotFoundThis error 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.
errs.FeatureVariableNotFoundThis error 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.
errs.FeatureEnvironmentDisabledThis error indicates that the feature flag is disabled for the current environment.

GetFeatureVariationVariables

To retrieve all variables associated with a feature flag, you need to call the GetFeatureVariationVariables 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.GetFeatureVariationVariables(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
errs.FeatureConfigNotFoundThis error 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.
errs.FeatureVariationNotFoundThis error 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.
errs.FeatureEnvironmentDisabledThis error indicates that the feature flag is disabled for the current environment.

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
errs.VisitorCodeInvalidThis error is returned 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/v3/types"
)

client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeChrome))

client.AddData(visitorCode,
types.NewPageViewWithTitle("https://url.com", "title", 3),
types.NewConversionWithRevenue(32, 10, false),
)

The AddData() method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.

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 using the flush method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the flush. Note that the TrackConversion method also sends out any previously associated data, just like the flush method. The same is true for getFeatureFlagVariationKey and GetFeatureVariable methods if an experimentation rule is triggered.

tip

Each visitor can only have one instance of associated data for most data types. However, CustomData is an exception. Visitors can have one instance of associated CustomData per customDataIndex.

Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
dataDataCustom data types, separated by a comma.
Exceptions thrown
TypeDescription
errs.VisitorCodeInvalidThis error is returned 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.NewCustomData(11, "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...))
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.

NewCustomData
NameTypeDescription
idintThe Index or unique ID of the custom data to be stored. This field is mandatory.
values...stringThe values of the custom data to be stored. This field is mandatory.
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(types.BrowserTypeChrome))

client.AddData(visitorCode, types.Browser(types.BrowserTypeSafari, 16.0))
NewBrowser
NameTypeDescription
browserTypeBrowserTypeList of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory.
version...float32Version of browser. This field is optional.
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.NewPageView("https://url.com", 3))

client.AddData(visitorCode, types.NewPageViewWithTitle("https://url.com", "title", 3))
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. This menas the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.

NewPageView
NameTypeDescription
urlstringThe URL of the page viewed. This field is mandatory.
referrers...intThe referrers of the viewed pages. This field is optional.
NewPageViewWithTitle
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.
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.NewConversion(32, false))

client.AddData(visitorCode, types.NewConversionWithRevenue(32, 10, false))
NewConversion
NameTypeDescription
goalIdintThe ID of the goal. This field is mandatory.
negative...boolDefines if the revenue is positive or negative. This field is optional.
NewConversionWithRevenue
NameTypeDescription
goalIdintThe ID of the goal. This field is mandatory.
revenuefloat64Conversion revenue. This field is optional.
negative...boolDefines 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.NewDevice(types.DeviceTypeDesktop))
NewDevice
NameTypeDescription
deviceTypeDeviceTypeList of devices: Phone, Tablet, Desktop. This field is mandatory.
UserAgent

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. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on Bot filtering.

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

client.AddData(visitorCode, types.NewUserAgent("visitor_user_agent"))
NewUserAgent
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 KameleoonClient 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") // uses 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.
timeouttime.DurationThe 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, err := 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(customDataIndex, cohorts...))
}

GetRemoteVisitorData

The GetRemoteVisitorData method allows you to retrieve custom data stored on remote Kameleoon servers for a visitor (specified using the visitorCode argument). If addData is true, this method automatically adds the retrieved data to a visitor without requiring you to make a separate AddData call. You must call NewClient to provide your siteCode before calling this method.

You also must have previously stored data on our remote servers, which you can add with any of the following tracking calls in the SDK:

  • FlushVisitor
  • FlushAll
  • GetFeatureVariationKey
  • GetFeatureVariable
  • IsFeatureActive

Using the GetRemoteVisitorData method along with the availability of our highly scalable servers provides a convenient way to quickly access and synchronize large amounts of data across all of the visitor's devices.

Arguments
NameTypeDescription
visitorCodestringThe visitor code for which you want to retrieve the assigned data. This field is mandatory.
addDataboolA boolean indicating whether the method should automatically add retrieved data for a visitor. This field is mandatory.
timeouttime.DurationThe 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
[]types.DataA slice of data assigned to the given visitor.
errorAn occurred error.

Example code

visitorCode := "visitorCode"
var visitorData []types.Data
var err error

// Visitor data will be fetched and automatically added for `visitorCode`
visitorData, err = client.GetRemoteVisitorData(visitorCode, true) // default timeout will be used
visitorData, err = client.GetRemoteVisitorData(visitorCode, true, time.Second) // 1000 milliseconds timeout

// If you only want to fetch data and add it yourself manually, set `addData` to `false`
visitorData, err = client.GetRemoteVisitorData(visitorCode, false) // default timeout will be used
visitorData, err = client.GetRemoteVisitorData(visitorCode, false, time.Second) // 1000 milliseconds timeout

GetVisitorWarehouseAudience()

Retrieves all audience data associated with the visitor in your data warehouse using the specified VisitorCode and WarehouseKey. The WarehouseKey is typically your internal user ID. The CustomDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method returns a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.

Arguments
NameTypeDescription
VisitorCodestringA unique visitor identification string, can't exceed 255 characters length.
CustomDataIndexintAn integer representing the index of the custom data you want to use to target your BigQuery Audiences.
WarehouseKeystringA unique key to identify the warehouse data (usually, your internal user ID). This field is optional.
Timeouttime.DurationThe 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. This field is optional.
note

Parameters are passed into the function as params of struct VisitorWarehouseAudienceParams to make some of them optional (WarehouseKey and Timeout).

Return value
TypeDescription
*types.CustomDataA CustomData instance confirming that the data has been added to the visitor.
errorAn occurred error.
Example code
customData, err = client.GetVisitorWarehouseAudience(VisitorWarehouseAudienceParams{
VisitorCode: "visitorCode",
CustomDataIndex: 10,
WarehouseKey: "warehouseKey", // optional
Timeout: 5 * time.Second, // optional
})

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 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/v3/types"
)

visitorCode, err := client.GetVisitorCode(req, resp)

client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeChrome))

client.AddData(visitorCode, types.NewConversionWithRevenue(32, 10, false))

client.FlushVisitor(visitorCode)

client.FlushAll()
Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory for FlushVisitor()
Exceptions thrown
TypeDescription
errs.VisitorCodeInvalidThis 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, Google Analytics 4, and 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. The SDK builds a tracking code for your active analytics solution based on the experiments that the visitor has triggered in the last 5 seconds. For more information about hybrid experimentation, see the Hybrid experimentation 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

Method getEngineTrackingCode() returns Kameleoon tracking code for the current visitor. Tracking code is built based the experiments that were triggered during the last 5 seconds.

Arguments
NameTypeDescription
visitorCodestringThe user's unique identifier. This field is mandatory.
Return value
TypeDescription
stringJavaScript code to be inserted in your page

Targeting conditions

The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions supported by this SDK, see Use visit history to target users.

You can also use your own external data to target users.