Go SDK
With the Go SDK, you can run experiments and activate feature flags. Integrating our SDK into your web-application is easy, and its footprint (memory and network usage) is low.
Getting started: For help getting started, see the developer guide.
Changelog: Latest version of the Go SDK: 3.6.1 Changelog.
SDK methods: For the full reference documentation of the Go SDK, see the reference section.
Developer guide
Follow this section to install and configure the SDK as well as learn about advanced features.
Getting started
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:
Key | Description |
---|---|
client_id | A client_id is required for authentication to the Kameleoon service. |
client_secret | A client_secret is required for authentication to the Kameleoon service. |
top_level_domain | The 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_duration | Sets 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_interval | This 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_timeout | Specifies 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. |
tracking_interval | Specifies the interval for tracking requests. All visitors who were evaluated for any feature flag or had data flushed will be included in this tracking request, which is performed once per interval. The minimum value is 100ms and the maximum value is 1s , which is also the default value. |
verbose_mode | Boolean value (true or false ) that turns on additional logging, including network requests and debug information. This field is deprecated and will be removed in SDK version 4.0.0 . Use logging.SetLogLevel instead. |
proxy_url | This sets the proxy host for all outgoing server calls made by the SDK. |
environment | Environment 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. |
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.
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.
You can customize the behavior of the SDK (for example, the environment or 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)
TrackingInterval: time.Second, // Optional (1000 ms 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")
Activating a feature flag
Assigning a unique ID to a user
To assign a unique ID to a user, you can use the GetVisitorCode()
method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode
that you would have generated. The ID is then set in a response headers cookie.
If you are using Kameleoon in Hybrid mode, calling the GetVisitorCode()
method ensures that the unique ID (visitor code) is shared between the application file (kameleoon.js) and the SDK.
Retrieving a flag configuration
To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.
To determine the status or variation of a feature flag for a specific user, you should use the GetVariation()
or IsFeatureActive()
method to retrieve the configuration based on the featureKey
.
The GetVariation()
method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the featureKey
and visitorCode
.
The IsFeatureActive()
method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.
If your feature flag has associated variables (such as specific behaviors tied to each variation) GetVariation()
also enables you to access the Variation
object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When params.Track=true
, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s tracking_interval
. By default, this interval is set to 1000 milliseconds (1 second).
The GetVariation()
method allows you to control whether tracking is done. If params.Track=false
, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting params.Track=false
is helpful when using the GetVariations()
method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article
Adding data points to target a user or filter / breakdown visits in reports
To target a user, ensure you've added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the AddData()
method to add these data points to the user's profile.
To retrieve data points that have been collected on other devices or to access past data points about a user (which would have been collected client-side if you are using Kameleoon in Hybrid mode), use the GetRemoteVisitorData()
method. This method asynchronously fetches data from our servers. However, it is important you call GetRemoteVisitorData()
before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation of a feature flag.
To learn more about available targeting conditions, read our detailed article on the subject.
Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here.
If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's Custom Data feature. Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the Flush*()
method to send the collected data to Kameleoon servers for analysis.
To ensure your results are accurate, it's recommended to filter out bots by using the UserAgent
data type.
Tracking flag exposition and goal conversions
When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the TrackConversion()
method and provide the required visitorCode
and goalId
parameters.
The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by tracking_interval
). If you prefer to send the request immediately, use the FlushVisitorInstantly()
method.
Sending events to analytics solutions
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the GetEngineTrackingCode()
method.
The GetEngineTrackingCode()
method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.
Cross-device experimentation
To support visitors who access your app from multiple devices, Kameleoon allows you to synchronize previously collected visitor data across each of the visitor's devices and reconcile their visit history across devices through cross-device experimentation.
Synchronizing custom data across devices
If you want to synchronize your Custom Data across multiple devices, Kameleoon provides a custom data synchronization mechanism.
To synchronize visitor data across multiple devices, Kameleoon provides a native synchronization mechanism. To use this feature, you need to create a Kameleoon custom data and set as a value the visitor identifier that uniquely identifies this user across multiple devices (internal user ID). The custom data should be configured as follows:
- Scope: Visitor
- Option "Use this custom data as a unique identifier for cross-device matching" turned ON.
After the custom data is set up, calling GetRemoteVisitorData()
makes the latest data accessible on any device.
See the following example of data synchronization between two devices:
// In this example Custom data with index `90` was set to "Visitor" scope on Kameleoon Platform.
const VisitorScopeCustomDataIndex = 90
kameleoonClient.AddData(visitorCode, types.NewCustomData(VisitorScopeCustomDataIndex, "your data"))
err := kameleoonClient.FlushVisitor(visitorCode)
// Before working with the data, call the `GetRemoteVisitorData` method.
_, err := kameleoonClient.GetRemoteVisitorData(visitorCode, true)
// After that the SDK on Device B will have an access to CustomData of Visitor scope defined on Device A.
// So "your data" will be available for targeting and tracking for the visitor.
Using custom data for session merging
Cross-device experimentation allows you to combine a visitor's history across each of their devices (history reconciliation). One of the powerful features that history reconciliation provides is the ability to merge different visitors sessions into one. To reconcile visit history, you can use CustomData
to provide a unique identifier for the visitor.
Follow the activating cross-device history reconciliation guide to set up your custom data on the Kameleoon platform
When your custom data is set up, you can use it in your code to merge a visitor's sessions.
Sessions with the same identifier will always see the same experiment variation and will be displayed as a single visitor in the Visitor view of your experiment's result pages.
The SDK configuration ensures that associated sessions always see the same variation of the experiment.
Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:
GetRemoteVisitorData()
with addedUniqueIdentifier(true)
- to retrieve data for all linked visitors.TrackConversion()
orFlush*()
with addedUniqueIdentifier(true)
data - to track some data for specific visitor that is associated with another visitor.
As the custom data you use as the identifier must be set to Visitor scope, you need to use cross-device custom data synchronization to retrieve the identifier with the GetRemoteVisitorData()
method on each device.
Here's an example of how to use custom data for session merging.
// In this example, `91` represents the index of the Custom Data
// configured as a unique identifier on Kameleoon Platform.
const MappingIndex = 91
const FeatureKey = "ff123"
// 1. Before the visitor is authenticated
// Retrieve the variation for an unauthenticated visitor.
// Assume `anonymousVisitorCode` is the randomly generated ID for that visitor.
anonymousVariation, err := kameleoonClient.GetVariation(anonymousVisitorCode, FeatureKey)
// 2. After the visitor is authenticated
// Assume `userId` is the visitor code of the authenticated visitor.
kameleoonClient.AddData(anonymousVisitorCode, types.NewCustomData(MappingIndex, userId))
err := kameleoonClient.FlushVisitorInstantly(anonymousVisitorCode)
// Indicate that `userId` is a unique identifier.
kameleoonClient.AddData(userId, types.NewUniqueIdentifier(true))
// 3. After the visitor has been authenticated
// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
userVariation, err := kameleoonClient.GetVariation(userId, FeatureKey)
isSameVariation := userVariation.Key == anonymousVariation.Key // true
// The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
err := kameleoonClient.TrackConversionRevenue(userId, 123, 10.0)
// Also, the linked visitors will share all fetched remote visitor data.
_, err := kameleoonClient.GetRemoteVisitorData(userId, true)
In this example, we have an application with a login page. Since we don't know the user ID at the moment of login, we use an anonymous visitor identifier generated by the GetVisitorCode()
method. After the user logs in, we can associate the anonymous visitor with the user ID and use it as a unique identifier for the visitor.
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 this SDK supports, see use visit history to target users.
You can also use your own external data to target users.
Logging
The SDK generates logs to reflect various internal processes and issues.
Log levels
The SDK supports configuring limiting logging by a log level.
import (
"development.kameleoon.net/sdk/go-sdk/v3/logging"
)
// The `NONE` log level allows no logging.
logging.SetLogLevel(logging.NONE)
// The `ERROR` log level allows to log only issues that may affect the SDK's main behaviour.
logging.SetLogLevel(logging.ERROR)
// The `WARNING` log level allows to log issues which may require an attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
logging.SetLogLevel(logging.WARNING)
//The `INFO` log level allows to log general information on the SDK's internal processes.
// It extends the `WARNING` log level.
logging.SetLogLevel(logging.INFO)
// The `DEBUG` log level allows to log extra information on the SDK's internal processes.
// It extends the `INFO` log level.
logging.SetLogLevel(logging.DEBUG)
Custom handling of logs
The SDK writes its logs to the console output by default. This behaviour can be overridden.
Logging limiting by a log level is performed apart from the log handling logic.
import (
"development.kameleoon.net/sdk/go-sdk/v3/logging"
"github.com/sirupsen/logrus"
)
type CustomLogger struct {
}
func NewCustomLogger() logging.LoggerWithLevel {
return &CustomLogger{}
}
func (dl CustomLogger) Log(level logging.LogLevel, message string) {
switch level {
case logging.NONE:
case logging.ERROR:
logrus.Error(message)
case logging.WARNING:
logrus.Warn(message)
case logging.INFO:
logrus.Info(message)
case logging.DEBUG:
logrus.Debug(message)
}
}
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
logging.SetLogLevel(logging.DEBUG) // Optional, defaults to `logging.WARNING`.
logging.SetLogger(NewCustomLogger())
Reference
This is a full reference documentation of the Go SDK.
Initialization
Create()
const siteCode = "sitecode"
config := &kameleoon.KameleoonClientConfig{
// ...
}
client, err := KameleoonClientFactory.Create(siteCode, config)
Arguments
Name | Type | Description |
---|---|---|
siteCode | string | This is a unique key of the Kameleoon project you are using with the SDK. This field is mandatory. |
cfg | *KameleoonClientConfig | Represents 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
Type | Description |
---|---|
KameleoonClient | An instance of the KameleoonClient that will be used to manage your experiments and feature flags. |
error | An 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
Name | Type | Description |
---|---|---|
siteCode | string | A Kameleoon siteCode. This field is mandatory. |
cfgPath | string | A 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
Type | Description |
---|---|
KameleoonClient | An instance of the KameleoonClient that will be used to manage your experiments and feature flags. |
error | An error occurred within Create . The error can be errs.SiteCodeIsEmpty or errs.ConfigCredentialsInvalid . |
Forget()
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.
const siteCode = "sitecode"
KameleoonClientFactory.Forget(siteCode)
Arguments
Name | Type | Description |
---|---|---|
siteCode | string | The 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
Type | Description |
---|---|
error | An error occurred during the initialization process. |
Feature flags and variations
IsFeatureActive() / IsFeatureActiveWithTracking()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track
parameter)
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.
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.
If you specify a visitorCode
, the IsFeatureActive
method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
const featureKey = "new_checkout"
// Check if a Feature Flag is active (ON / OFF)
hasNewCheckout, err := client.IsFeatureActive(visitorCode, featureKey)
// disabling tracking
hasNewCheckout, err := client.IsFeatureActiveWithTracking(visitorCode, featureKey, false)
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
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
featureKey | string | The key of the feature you want to expose to a user. This field is mandatory. |
isUniqueIdentifier (Deprecated) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
track | bool | A parameter of the IsFeatureActiveWithTracking method to enable or disable tracking of the feature evaluation. IsFeatureActive(visitorCode, featureKey) is equivalent to IsFeatureActiveWithTracking(visitorCode, featureKey, true) . |
Return value
Type | Description |
---|---|
bool | Value of the feature flag that is registered for a given visitorCode. |
Exceptions thrown
Type | Description |
---|---|
errs.FeatureConfigNotFound | This 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.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
GetVariation()
- 📨 Sends Tracking Data to Kameleoon (depending on the
params.Track
parameter)
Retrieves the Variation
assigned to a given visitor for a specific feature flag.
This method takes a visitorCode
and featureKey
as mandatory arguments. The params.Track
argument is optional and defaults to true
.
It returns the assigned Variation
for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation
for the given feature flag.
Ensure that proper error handling is implemented in your code to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
const featureKey = "new_checkout"
variation, err := client.GetVariation(visitorCode, featureKey)
// disabling tracking
variation, err := client.GetVariation(visitorCode, featureKey, kameleoon.NewGetVariationOptParams.Track(false))
if err != nil {
// handle error
}
// Fetch a variable value for the assigned variation
title := variation.Variables["title"].Value
switch (variation.Key) {
case "on":
// Main variation key is selected for visitorCode
case "alternative_variation":
// Alternative variation key
default:
// Default variation key
}
Arguments
Name | Type | Description | Default |
---|---|---|---|
visitorCode (required) | string | Unique identifier of the user. | |
featureKey (required) | string | Key of the feature you want to expose to a user. | |
params.Track (optional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
Type | Description |
---|---|
Variation | An assigned variation to a given visitor for a specific feature flag. |
Exceptions thrown
Type | Description |
---|---|
errs.VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
errs.FeatureNotFound | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed on your application). |
errs.FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development). |
GetVariations()
- 📨 Sends Tracking Data to Kameleoon (depending on the
params.Track
parameter)
Retrieves a map of Variation
objects assigned to a given visitor across all feature flags.
This method iterates over all available feature flags and returns the assigned Variation
for each flag associated with the specified visitor. It takes visitorCode
as a mandatory argument, while OnlyActive
and params.Track
are optional.
- If
OnlyActive
is set totrue
, the methodGetVariations()
will return feature flags variations provided the user is not bucketed with theoff
variation. - The
params.Track
parameter controls whether or not the method will track the variation assignments. By default, it is set totrue
. If set tofalse
, the tracking will be disabled.
The returned map consists of feature flag keys as keys and their corresponding Variation
as values. If no variation is assigned for a feature flag, the method returns the default Variation
for that flag.
Proper error handling should be implemented to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
variations, err := client.GetVariations(visitorCode)
// all active variations
variations, err := client.GetVariations(visitorCode, kameleoon.NewGetVariationsOptParams().OnlyActive(true))
// disable tracking
variations, err := client.GetVariations(visitorCode, kameleoon.NewGetVariationsOptParams().Track(false))
if err != nil {
// handle error
}
Arguments
Name | Type | Description | Default |
---|---|---|---|
visitorCode (required) | string | Unique identifier of the user. | |
OnlyActive (optional) | boolean | An optional parameter indicating whether to return variations for active (true ) or all (false ) feature flags. | false |
params.Track (optional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
Type | Description |
---|---|
map[string]Variation | Map that contains the assigned Variation objects of the feature flags using the keys of the corresponding features. |
Exceptions thrown
Type | Description |
---|---|
errs.VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is required. |
OnlyActive | bool | An optional parameter indicating whether to return variations for active (true ) or all (false ) feature flags (Defaults to false ). |
Track | bool | An optional parameter to enable or disable tracking of the feature evaluation (Defaults to true ). |
Return value
Type | Description |
---|---|
map[string]Variation | Map that contains the assigned Variations of the feature flags using the keys of the corresponding features. |
Exceptions thrown
Type | Description |
---|---|
VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
GetFeatureVariationKey()
- 📨 Sends Tracking Data to Kameleoon
This method is deprecated and will be removed in SDK version 4.0.0
. Use GetVariation()
instead.
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.
Don't forget to handle potential exceptions with proper error handling in your code. Check out the example code for guidance.
If you specify a visitorCode
, the GetFeatureVariationKey
method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
// 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
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
featureKey | string | The key of the feature you want to expose to a user. This field is mandatory. |
isUniqueIdentifier (Deprecated) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Return value
Type | Description |
---|---|
string | Variation key of the feature flag that is registered for a given visitorCode. |
Exceptions thrown
Type | Description |
---|---|
errs.FeatureConfigNotFound | This 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.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
errs.FeatureEnvironmentDisabled | This error indicates that the feature flag is disabled for the current environment. |
GetActiveFeatureListForVisitor()
The GetActiveFeatureListForVisitor()
method takes a visitorCode
parameter. When you call this method with a specific visitorCode
, the method returns 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. For example, see the following code:
This method is deprecated and will be removed in SDK version 4.0.0
. Use GetActiveFeatures()
instead.
arrayFeatureFlagKeys, err := client.GetActiveFeatureListForVisitor(visitorCode)
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
Return value
Type | Description |
---|---|
[]string | List of feature flag keys that are active for a specific visitorCode . |
Exceptions thrown
Type | Description |
---|---|
errs.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
GetActiveFeatures()
This method is deprecated and will be removed in SDK version 4.0.0
. Use GetVariations()
instead.
The GetActiveFeatures()
method retrieves information about the active feature flags that are available for the specified visitor code.
Don't forget to handle potential exceptions with proper error handling in your code. For example, see the following code:
activeFeatures, err := client.GetActiveFeatures(visitorCode)
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
Return value
Type | Description |
---|---|
map[string]types.Variation | Map that contains the assigned variations of the active features using the active feature IDs as keys. |
Exceptions thrown
Type | Description |
---|---|
errs.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
GetFeatureList()
Returns a list of feature flag keys currently available for the SDK.
arrayFeatureKeys := client.GetFeatureList()
Return value
Type | Description |
---|---|
[]string | List of feature flag keys |
Variables
GetFeatureVariable()
- 📨 Sends Tracking Data to Kameleoon
This method is deprecated and will be removed in SDK version 4.0.0
. Use GetVariation()
instead.
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.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
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
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
featureKey | string | The key of the feature you want to expose to a user. This field is mandatory. |
variableKey | string | The name of the variable for which you want to get a value. This field is mandatory. |
isUniqueIdentifier (Deprecated) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Return value
Type | Description |
---|---|
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
Type | Description |
---|---|
errs.FeatureConfigNotFound | This 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.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
errs.FeatureVariationNotFound | This 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.FeatureVariableNotFound | This 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.FeatureEnvironmentDisabled | This error indicates that the feature flag is disabled for the current environment. |
GetFeatureVariationVariables()
This method is deprecated and will be removed in SDK version 4.0.0
. Use GetVariation()
instead.
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
Name | Type | Description |
---|---|---|
featureKey | string | The key of the feature flag you want to obtain. This field is mandatory. |
variationKey | string | The key of the variation you want to obtain. This field is mandatory. |
Return value
Type | Description |
---|---|
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
Type | Description |
---|---|
errs.FeatureConfigNotFound | This 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.FeatureVariationNotFound | This 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.FeatureEnvironmentDisabled | This error indicates that the feature flag is disabled for the current environment. |
Visitor data
GetVisitorCode()
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:
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.
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.
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.
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
Name | Type | Description |
---|---|---|
request | *fasthttp.Request | The current fasthttp.Request object should be passed as the first parameter. This field is mandatory. |
response | *fasthttp.Response | The current fasthttp.Response object should be passed as the second parameter. This field is mandatory. |
defaultVisitorCode | string | This 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
Type | Description |
---|---|
(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 Message | Description | |
---|---|---|
errs.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
AddData()
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*()
.
The TrackConversion()
method also sends out any previously associated data, just like the Flush*()
. The same holds true for GetVariation()
and GetVariations()
methods if an experimentation rule is triggered.
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 index.
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),
)
Arguments
Name | Type | Description |
---|---|---|
visitorCode (required) | string | Unique identifier of the user. |
allData (required) | ...types.Data | Collection of Kameleoon data types. |
Exceptions
Type | Description |
---|---|
errs.VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
FlushAll() / FlushVisitor() / FlushVisitorInstantly()
- 📨 Sends Tracking Data to Kameleoon
FlushAll()/FlushVisitor()/FlushVisitorInstantly()
methods take the Kameleoon data associated with the visitor, then send a tracking request along with all of the data that were added previously using the AddData()
method, that has not yet been sent when calling one of these methods. Flush*()
is non-blocking as the server call is made asynchronously.
Flush*()
allows you to control when the data associated with a given visitorCode
is sent to our servers. For instance, if you call AddData()
a dozen times, it would be inefficient to send data to the server after each time AddData()
is invoked, so all you have to do is call Flush*()
once at the end.
The FlushVisitor()/FlushVisitorInstantly()
method uses visitorCode
as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode
and set the isUniqueIdentifier
parameter to true
, the SDK links the flushed data with the visitor associated with the specified identifier.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
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) // Interval tracking (most performant way for tracking)
client.FlushAll() // Interval tracking for all visitors' unsent data
client.FlushVisitorInstantly(visitorCode) // Instant tracking
client.FlushAll(true) // Instant tracking for all visitors' unsent data
// if you operate with unique ID
client.AddData(types.NewUniqueIdentifier(true))
client.FlushVisitor(visitorCode)
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory for FlushVisitor()/FlushVisitorInstantly() . |
isUniqueIdentifier (Deprecated) | bool | A parameter of the FlushVisitor method for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Exceptions thrown
Type | Description |
---|---|
errs.VisitorCodeInvalid | This exception is raised when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
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
Name | Type | Description |
---|---|---|
siteCode | string | The siteCode of the KameleoonClient instance to be removed from the KameleoonClientFactory . This field is mandatory. |
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 that, since a server call is required, this mechanism is asynchronous.
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...))
}
Arguments
Name | Type | Description |
---|---|---|
key | string | The 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. |
timeout | int | The 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
Type | Description |
---|---|
[]byte | This returns the information associated with retrieving data for a specific key. The result needs to be decoded using the json.Unmarshal () function. |
Exceptions thrown
Type | Description |
---|---|
error | Error indicating that the request timed out. |
GetRemoteVisitorData()
GetRemoteVisitorData()
is an asynchronous method for retrieving Kameleoon Visits Data for the VisitorCode
from the Kameleoon Data API. The method adds the data to storage for other methods to use when making targeting decisions.
Data obtained using this method plays an important role when you want to:
- use data collected from other devices.
- access a user's history, such as previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.
By default, GetRemoteVisitorData()
automatically retrieves the latest stored custom data with Scope=Visitor
and attaches them to the visitor without the need to call the method AddData()
. It is particularly useful for synchronizing custom data between multiple devices.
The parameter IsUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The IsUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Using parameters in GetRemoteVisitorData()
The GetRemoteVisitorData()
method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you're targeting based on goals, experiments, or variations, the same approach applies across all data types.
For example, let's say you want to retrieve data on visitors who completed a goal "Order transaction". You can specify parameters within the GetRemoteVisitorData()
method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the PreviousVisitAmount
parameter to 5 and Conversions
to true.
The flexibility shown in this example is not limited to goal data. You can use parameters within the GetRemoteVisitorData()
method to retrieve data on a variety of visitor behaviors.
Arguments of GetRemoteVisitorData
Name | Type | Description |
---|---|---|
visitorCode | string | The visitor code for which you want to retrieve the assigned data. This field is mandatory. |
addData | bool | A boolean indicating whether the method should automatically add retrieved data for a visitor. This field is mandatory. |
timeout | time.Duration | The 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. |
Arguments of GetRemoteVisitorDataWithFilter
Name | Type | Description |
---|---|---|
visitorCode | string | The visitor code for which you want to retrieve the assigned data. This field is mandatory. |
addData | bool | A boolean indicating whether the method should automatically add retrieved data for a visitor. This field is mandatory. |
filter | types.RemoteVisitorDataFilter | Filter for specifying what data should be retrieved from visits. This field is mandatory. |
timeout | time.Duration | The 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. |
Arguments of GetRemoteVisitorDataWithOptParams
The GetRemoteVisitorDataWithOptParams
method is deprecated. Please use GetRemoteVisitorDataWithFilter
and UniqueIdentifier
. instead
Name | Type | Description |
---|---|---|
visitorCode | string | The visitor code for which you want to retrieve the assigned data. This field is mandatory. |
addData | bool | A boolean indicating whether the method should automatically add retrieved data for a visitor. This field is mandatory. |
filter | types.RemoteVisitorDataFilter | Filter for specifying what data should be retrieved from visits. This field is mandatory. |
params | kameleoon.RemoteVisitorDataOptParams | Optional parameters. |
Here is the list of kameleoon.RemoteVisitorDataOptParams
fields:
Name | Type | Description |
---|---|---|
IsUniqueIdentifier (optional) (Deprecated) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false . |
Timeout (optional) | time.Duration | The 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. |
The default value of kameleoon.RemoteVisitorDataOptParams
which is types.RemoteVisitorDataFilter{PreviousVisitAmount: 1, CurrentVisit: true, CustomData: true}
, can be gotten with types.DefaultRemoteVisitorDataFilter()
function.
Here is the list of available types.RemoteVisitorDataFilter
options:
Name | Type | Description | Default |
---|---|---|---|
PreviousVisitAmount (optional) | int | Number of previous visits to retrieve data from. Number between 1 and 25 | 1 |
CurrentVisit (optional) | bool | If true, current visit data will be retrieved | true |
CustomData (optional) | bool | If true, custom data will be retrieved. | true |
PageViews (optional) | bool | If true, page data will be retrieved. | false |
Geolocation (optional) | bool | If true, geolocation data will be retrieved. | false |
Device (optional) | bool | If true, device data will be retrieved. | false |
Browser (optional) | bool | If true, browser data will be retrieved. | false |
OperatingSystem (optional) | bool | If true, operating system data will be retrieved. | false |
Conversions (optional) | bool | If true, conversion data will be retrieved. | false |
Experiments (optional) | bool | If true, experiment data will be retrieved. | false |
Kcs (optional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
VisitorCode (optional) | bool | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode , always receives the same variant across visits for Cross-device experimentation. | true |
Return value
Type | Description |
---|---|
[]types.Data | A slice of data assigned to the given visitor. |
error | An occurred error. |
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
// If you operate with unique ID
client.AddData(types.NewUniqueIdentifier(true))
visitorData, err = client.GetRemoteVisitorData(visitorCode, true)
// If you want to fetch custom list of data types
var visitorData = client.GetRemoteVisitorDataWithFilter(
visitorCode,
true,
types.RemoteVisitorDataFilter{PreviousVisitAmount: 10, CustomData: true, Conversion: true, Experiments: true},
// default timeout will be used
)
// or
var visitorData = client.GetRemoteVisitorDataWithFilter(
visitorCode,
true,
types.RemoteVisitorDataFilter{PreviousVisitAmount: 10, CustomData: true, Conversion: true, Experiments: true},
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 of GetVisitorWarehouseAudience
Name | Type | Description |
---|---|---|
VisitorCode | string | A unique visitor identification string, can't exceed 255 characters length. |
CustomDataIndex | int | An integer representing the index of the custom data you want to use to target your BigQuery Audiences. |
WarehouseKey | string | A unique key to identify the warehouse data (usually, your internal user ID). This field is optional. |
Timeout | time.Duration | The 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. |
Arguments of GetVisitorWarehouseAudienceWithOptParams
Name | Type | Description |
---|---|---|
visitorCode | string | A unique visitor identification string, can't exceed 255 characters length. |
customDataIndex | int | An integer representing the index of the custom data you want to use to target your BigQuery Audiences. |
params | kameleoon.VisitorWarehouseAudienceOptParams | Optional parameters. |
Here is the list of kameleoon.VisitorWarehouseAudienceOptParams
fields:
Name | Type | Description |
---|---|---|
WarehouseKey | string | A unique key to identify the warehouse data (usually, your internal user ID). This field is optional. |
Timeout | time.Duration | The 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. |
For GetVisitorWarehouseAudience
method parameters are passed into the function as params
of struct VisitorWarehouseAudienceParams
to make some of them optional (WarehouseKey
and Timeout
).
For GetVisitorWarehouseAudienceWithOptParams
method only optional parameters are passed into the function as params
of struct VisitorWarehouseAudienceOptParams
.
:::
Return value
Type | Description |
---|---|
*types.CustomData | A CustomData instance confirming that the data has been added to the visitor. |
error | An occurred error. |
Example code
customData, err = client.GetVisitorWarehouseAudience(VisitorWarehouseAudienceParams{
VisitorCode: "visitorCode",
CustomDataIndex: 10,
WarehouseKey: "warehouseKey", // optional
Timeout: 5 * time.Second, // optional
})
customData, err = c.GetVisitorWarehouseAudienceWithOptParams(
"visitorCode", 10, VisitorWarehouseAudienceOptParams{WarehouseKey: "warehouseKey", Timeout: 5 * time.Second})
SetLegalConsent()
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.
visitorCode, err := kameleoonClient.GetVisitorCode(req, resp)
err := kameleoonClient.SetLegalConsent(visitorCode, true, resp)
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is required. |
consent | bool | A 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.Response | The HTTP response where values in the cookies will be adjusted based on the legal consent status. This field is optional. |
Exceptions thrown
Type | Description |
---|---|
errs.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
Goals and third-party analytics
TrackConversion()
- 📨 Sends Tracking Data to Kameleoon
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.
The parameter isUniqueIdentifier
is deprecated. Please use UniqueIdentifier
instead.
The isUniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
import (
"github.com/Kameleoon/client-go/v3/types"
)
const goalID = 83023
client.TrackConversion(visitorCode, goalID)
client.TrackConversionRevenue(visitorCode, goalID, 10.0)
// if you operate with unique ID
client.AddData(types.NewUniqueIdentifier(true))
client.TrackConversion(visitorCode, goalID)
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
goalId | int | The ID of the goal. This field is mandatory. |
revenue | float64 | A parameter of the TrackConversionRevenue method to specify the revenue of the conversion. TrackConversion(visitorCode, goalID) is equivalent to TrackConversionRevenue(visitorCode, goalID, 0.0) . |
isUniqueIdentifier (Deprecated) | bool | Specifies that the visitorCode is a unique identifier. If not provided, the default value is false . The field is optional. |
Exceptions thrown
Type | Description |
---|---|
errs.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
GetEngineTrackingCode()
Kameleoon offers built-in integrations with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To ensure that you can track and analyze your server-side experiments, Kameleoon provides the method GetEngineTrackingCode()
to automatically send exposure events to the analytics solution you are using. The SDK builds a tracking code for your active analytics solution based on the experiments the visitor has triggered in the last 5 seconds. Please refer to our hybrid experimentation for more information on implementing this method.
You must implement both the Go SDK and our Kameleoon JavaScript tag to benefit from this feature. 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.
The following string will 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 users have been assigned to.
engineTrackingCode := kameleoonClient.GetEngineTrackingCode(visitorCode)
Arguments
Name | Type | Description |
---|---|---|
visitorCode (required) | string | Unique identifier of the user. |
Return value
Type | Desription |
---|---|
string | JavaScript code to be inserted in your page |
Events
OnUpdateConfiguration()
kameleoonClient.OnUpdateConfiguration(
// configuration was updated
)
The OnUpdateConfiguration
method allows you to handle the event when configuration has updated data. It takes one input parameter, handler. The handler that will be called when the configuration is updated using a real-time configuration event.
Arguments
Name | Type | Description |
---|---|---|
handler | func() | The handler that will be called when the configuration is updated using a real-time configuration event. |
Data types
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.NewBrowser(types.BrowserTypeChrome))
client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeSafari, 16.0))
Name | Type | Description |
---|---|---|
browserType (required) | BrowserType | List of browsers: BrowserTypeChrome , BrowserTypeIE , BrowserTypeFirefox , BrowserTypeSafari , BrowserTypeOpera , BrowserTypeOther . |
version (optional) | float32 | Version of the browser, floating point number represents major and minor version of the browser |
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
Name | Type | Description |
---|---|---|
goalId | int | The ID of the goal. This field is mandatory. |
negative | ...bool | Defines if the revenue is positive or negative. This field is optional. |
NewConversionWithRevenue
Name | Type | Description |
---|---|---|
goalId | int | The ID of the goal. This field is mandatory. |
revenue | float64 | Conversion revenue. This field is optional. |
negative | ...bool | Defines if the revenue is positive or negative. This field is optional. |
Cookie
Cookie
contains information about the cookie stored on the visitor's device.
Each visitor can only have one Cookie
. Adding second Cookie
overwrites the first one.
cookie := types.NewCookie(map[string]string{
"k1": "v1",
"k2": "v2",
})
client.AddData(visitorCode, cookie)
Name | Type | Description |
---|---|---|
cookies | map[string]string | A string object map consisting of cookie keys and values. This field is required. |
Geolocation
Geolocation
contains the visitor's geolocation details.
- Each visitor can have only one
Geolocation
. Adding a secondGeolocation
overwrites the first one.
client.AddData(visitorCode, types.NewGeolocation("France", "Île-de-France", "Paris"))
client.AddData(visitorCode, types.NewGeolocationWithCoords(48.856667, 2.352222, "France", "Île-de-France", "Paris"))
Name | Type | Description |
---|---|---|
country (required) | string | The country of the visitor. |
region (optional) | string | The region of the visitor. |
city (optional) | string | The city of the visitor. |
postalCode (optional) | string | The postal code of the visitor. |
latitude (optional) | float64 | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
longitude (optional) | float64 | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
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...))
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
Name | Type | Description |
---|---|---|
id | int | The Index or unique ID of the custom data to be stored. This field is mandatory. |
values | ...string | The values of the custom data to be stored. This field is mandatory. |
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
Name | Type | Description |
---|---|---|
deviceType | DeviceType | List of devices: Phone, Tablet, Desktop. This field is mandatory. |
OperatingSystem
OperatingSystem
contains information about the operating system on the visitor's device.
Each visitor can only have one OperatingSystem
. Adding a second OperatingSystem
overwrites the first one.
client.AddData(visitorCode, types.NewOperatingSystem(types.OperatingSystemTypeWindows))
Name | Type | Description |
---|---|---|
type | types.OperatingSystemType | List of operating systems: Windows, Mac, iOS, Linux, Android and WindowsPhone. This field is required. |
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))
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
Name | Type | Description |
---|---|---|
url | string | The URL of the page viewed. This field is mandatory. |
referrers | ...int | The referrers of the viewed pages. This field is optional. |
NewPageViewWithTitle
Name | Type | Description |
---|---|---|
url | string | The URL of the page viewed. This field is mandatory. |
title | string | The title of the page viewed. This field is mandatory. |
referrers | ...int | The referrers of the viewed pages. This field is optional. |
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
Name | Type | Description |
---|---|---|
value | string | The User-Agent value that will be sent with tracking requests. This field is mandatory. |
UniqueIdentifier
If you don't add UniqueIdentifier
for a visitor, visitorCode
is used as the unique visitor identifier, which is useful for Cross-device experimentation. When you add UniqueIdentifier
for a visitor, the SDK links the flushed data with the visitor associated with the specified identifier.
The UniqueIdentifier
can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode
that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
client.AddData(types.NewUniqueIdentifier(true))
NewUniqueIdentifier
Name | Type | Description |
---|---|---|
value | bool | Parameter for specifying if the visitor_code is a unique identifier. This field is mandatory. |
Returned Types
Variation
Variation
contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
Name | Type | Description |
---|---|---|
Key | string | The unique key identifying the variation. |
VariationID | *int | The ID of the assigned variation (or nil if it's the default variation). |
ExperimentID | *int | The ID of the experiment associated with the variation (or nil if default). |
Variables | map[string]Variable | A map containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated. |
- The
Variation
object provides details about the assigned variation and its associated experiment, while theVariable
object contains specific details about each variable within a variation. - Ensure that your code handles the case where
VariationID
orExperimentID
may benil
, indicating a default variation. - The
Variables
map might be empty if no variables are associated with the variation.
Example code
// Retrieving the variation key
var variationKey string = variation.Key
// Retrieving the variation id
var variationID *int = variation.VariationID
// Retrieving the experiment id
var experimentID *int = variation.ExperimentID
// Retrieving the variables map
var variables map[string]Variable = variation.Variables
Variable
Variable
contains information about a variable associated with the assigned variation.
Name | Type | Description |
---|---|---|
Key | string | The unique key identifying the variable. |
Type | string | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS. |
Value | interface{} | The value of the variable, which can be of the following types: bool, int, float, string, map, array. |
Example code
// Retrieving the variables map
var variables map[string]Variable = variation.Variables
// Variable type can be retrieved for further processing
var variableType string = variables["isDiscount"].Type
// Retrieving the variable value by key
var isDiscount bool = variables["isDiscount"].Value.(bool)
// Variable value can be of different types
var title string = variables["title"].Value.(string)