> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK

> Integrate the Kameleoon Go SDK to run experiments and activate feature flags in Go web applications and services.

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](#developer-guide).

**Changelog**: Latest version of the Go SDK: 3.20.0 [Changelog](https://github.com/Kameleoon/client-go/blob/master/CHANGELOG.md).

**SDK methods**: For the full reference documentation of the Go SDK, see the [reference](#reference) section.

## Developer guide

Follow this section to install and configure the SDK, and learn about advanced features.

### Getting started

#### Installing the Go client

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

```shell theme={null}
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 lets you customize the SDK's behavior. You can download a sample configuration file [here](/assets/developer-docs/sdks/web-sdks/client-configs/client-go.yaml).

We recommend installing this file to the default path `/etc/kameleoon/client-go.yaml`, which will be read automatically. If you need to customize this path, you can provide an additional argument to the `NewClient()` method. Either specify a string that indicates an alternative path to the configuration file, or 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Default value        |
| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `ClientID` / `client_id` <Badge color="red" size="sm">required</Badge>                   | Required for authentication to the Kameleoon service. To find your `client_id`, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation.                                                                                                                                                                                                                                                                                                                                                                                                                           |                      |
| `ClientSecret` / `client_secret` <Badge color="red" size="sm">required</Badge>           | Required for authentication to the Kameleoon service. To find your `client_secret`, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation.                                                                                                                                                                                                                                                                                                                                                                                                                       |                      |
| `SessionDuration` / `session_duration` <Badge color="green" size="sm">optional</Badge>   | Designates the predefined 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.                                                                                                                                                                                                                                                                                                                                                                                 | `30` minutes         |
| `RefreshInterval` / `refresh_interval` <Badge color="green" size="sm">optional</Badge>   | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. Additionally, we offer a [streaming mode](/developer-docs/feature-experimentation/technical-reference/technical-considerations/#streaming-premium-option) that uses server-sent events (SSE) to push new configurations to the SDK automatically and apply new configurations in real-time, without any delays. | `60` minutes         |
| `DefaultTimeout` / `default_timeout` <Badge color="green" size="sm">optional</Badge>     | Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to 30 seconds or more if you do not have a stable connection. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value.                                                                                                                                                                                                                                                    | `10000` milliseconds |
| `TrackingInterval` / `tracking_interval` <Badge color="green" size="sm">optional</Badge> | Specifies the interval for tracking requests in milliseconds. All visitors who Kameleoon evaluated for any feature flag or had data flushed are included in this tracking request, which the SDK performs once per interval. The minimum value is `1000` ms, which is also the default, and the maximum value is `5000` ms.                                                                                                                                                                                                                                                                                                  | `1000` milliseconds  |
| `Environment` / `environment` <Badge color="green" size="sm">optional</Badge>            | Environment from which the feature flag’s configuration is to be used. The value can be `production`, `staging`, `development`. See the [managing environments](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/manage-environments) article for details.                                                                                                                                                                                                                                                                                                                                  | `production`         |
| `TopLevelDomain` / `top_level_domain` *(required in hybrid mode)*                        | 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.                                                                                                                                                                                                                                                                                                                                                                                                | `""`                 |
| `ProxyUrl` / `proxy_url` <Badge color="green" size="sm">optional</Badge>                 | Sets the proxy host for all outgoing server calls made by the SDK.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | `""`                 |
| `NetworkDomain` / `network_domain` <Badge color="green" size="sm">optional</Badge>       | Custom domain used by SDKs for outgoing requests, often for proxying. Must be a valid domain (e.g., example.com or sub.example.com). Invalid formats default to Kameleoon's value.                                                                                                                                                                                                                                                                                                                                                                                                                                           | `""`                 |
| `VerboseMode` / `verbose_mode` *(deprecated)*                                            | 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`](#log-levels) instead.                                                                                                                                                                                                                                                                                                                                                                                 | `false`              |

<Note>
  To learn more about `client_id` and `client_secret`, and instructions on how to obtain them, please refer to this [article](/user-manual/account-and-team-management/users-and-teams/api-credentials). It's worth noting that our Go SDK utilizes the Automation API and follows the OAuth 2.0 client credentials flow.
</Note>

#### Initializing the Kameleoon Client

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

You can customize the behavior of the SDK (for example, the environment or the credentials) by providing a [configuration object](#additional-configuration).

```go theme={null}
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)
    NetworkDomain:    "example.com", // Optional
}
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 the example above, the configuration is loaded every time. To load it once, use `CreateFromFile`.

// 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()`](#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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation), calling the `GetVisitorCode()` method ensures that the unique ID (**visitor code**) is shared between the application file `engine.js` (previously named, `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()`](#getvariation) or [`IsFeatureActive()`](#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`](#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 `GetVariationOptParams.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`](#additional-configuration). By default, this interval is set to 1000 milliseconds (1 second).

The `GetVariation()` method allows you to control whether tracking is done. If `GetVariationOptParams.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 `GetVariationOptParams.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](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics)

##### 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()`](#adddata) method to add these data points to the user's profile.

To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the [`GetRemoteVisitorData()`](#getremotevisitordata) method. This method asynchronously fetches data from the servers. It is important to 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.

To learn more about available targeting conditions, see the [detailed article on the subject](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

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](/user-manual/experiment-analytics/analyze-results/results-page-settings#breakdown-audience).

If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's [Custom Data feature](#customdata). Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the [`Flush*()`](#flushall--flushvisitor--flushvisitorinstantly) method to send the collected data to Kameleoon servers for analysis.

<Note>
  To ensure your results are accurate, it's recommended to filter out bots by using the [`UserAgent`](#useragent) data type.
</Note>

##### 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()`](#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`](#additional-configuration)). If you prefer to send the request immediately, use the [`FlushVisitorInstantly()`](#flushall--flushvisitor--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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/). Then, use the [`GetEngineTrackingCode()`](#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 an app from multiple devices, Kameleoon allows the synchronization of previously collected visitor data across each of the visitor's devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the [article on cross-device experimentation](/developer-docs/cross-device-experimentation).

#### Synchronizing custom data across devices

Although custom mapping synchronization is used to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required:

**Same user ID across devices**
If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the `GetRemoteVisitorData()` method when you want to sync the data collected between multiple devices.

**Multi-server instances with consistent IDs**
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with `GetRemoteVisitorData()`) is sufficient without additional custom mapping sync.

Customers who need additional data can refer to the [`GetRemoteVisitorData()`](#getremotevisitordata) method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the `visitorCode`, which can also be referred to as `userId`) is used consistently between the two devices for accurate data retrieval.

<Note>
  If you want to sync collected data in real time, you need to choose the scope **Visitor** for your custom data.
</Note>

```go title="Device A" theme={null}
// In this example, Custom data with index `90` was set to "Visitor" scope in Kameleoon.
const VisitorScopeCustomDataIndex = 90

kameleoonClient.AddData(visitorCode, types.NewCustomData(VisitorScopeCustomDataIndex, "your data"))
err := kameleoonClient.FlushVisitor(visitorCode)
```

```go title="Device B" theme={null}
// Before working with the data, call the `GetRemoteVisitorData` method.
_, err := kameleoonClient.GetRemoteVisitorData(visitorCode, true)

// After calling the method, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
// So, "your data" will be available for targeting and tracking the visitor.
```

#### Using custom data for session merging

[Cross-device experimentation](/developer-docs/cross-device-experimentation) allows for combining a visitor's history across each of their devices (history reconciliation). History reconciliation allows merging different visitor sessions into one. To reconcile visit history, use [`CustomData`](#customdata) to provide a unique identifier for the visitor. For more information, see the [dedicated documentation](/developer-docs/cross-device-experimentation/#activating-cross-device-history-reconciliation).

After cross-device reconciliation is enabled, calling [`GetRemoteVisitorData()`](#getremotevisitordata) with the parameter `userId` retrieves all known data for a given user.

Sessions with the same identifier will always be shown the same variation in an experiment. In the Visitor view of your experiment's results pages, these sessions will appear as a single visitor.

The SDK configuration ensures that associated sessions always see the same variation of the experiment. However, there are some limitations regarding cross-device variation allocation. These limitations are outlined [here](/developer-docs/cross-device-experimentation#critical-points-and-practical-insights).

Follow the [activating cross-device history reconciliation](#cross-device-experimentation) guide to set up your custom data on the Kameleoon platform.

Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:

* `GetRemoteVisitorData()` with added `UniqueIdentifier(true)` - to retrieve data for all linked visitors.
* [`TrackConversion()`](#trackconversion) or [`Flush*()`](#flushall--flushvisitor--flushvisitorinstantly) with added `UniqueIdentifier(true)` data - to track some data for specific visitor that is associated with another visitor.

<Tip>
  As the custom data you use as the identifier must be set to **Visitor scope**, you need to use [cross-device custom data synchronization](/developer-docs/cross-device-experimentation) to retrieve the identifier with the [`GetRemoteVisitorData()`](#getremotevisitordata) method on each device.
</Tip>

Here's an example of how to use custom data for session merging.

```go theme={null}
// In this example, `91` represents the Custom Data's index
// configured as a unique identifier in Kameleoon.
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 authenticated visitor's visitor code.
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)

// Additionally, the linked visitors will share all fetched remote visitor data.
_, err := kameleoonClient.GetRemoteVisitorData(userId, true)
```

In this example, the application has a login page. Since the user ID is unknown at the moment of login, an anonymous visitor identifier generated by the [`GetVisitorCode()`](#getvisitorcode) method is used. After the user logs in, the anonymous visitor is associated with the user ID and used as a unique identifier for the visitor.

### Using a custom bucketing key

By default, Kameleoon uses a unique, anonymous visitor ID (`visitorCode`) to assign users to feature flag variations. This ID is typically generated and stored on the user's device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag.

The **Custom Bucketing Key** option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon's assignment logic uses your specified key instead of the default `visitorCode`.

#### Use cases

Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:

* **Account-level or organizational experiments:** For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an `accountId`. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.

By implementing a custom bucketing key, you ensure greater consistency and accuracy in your experiments, leading to more reliable results and a better user experience.

#### Technical details

When you configure a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your application's data:

```go theme={null}
client.AddData(visitorCode, types.NewCustomData(index, "newVisitorCode"))
```

* **Providing the custom key:** You provide your custom identifier to the Kameleoon SDK using the [`AddData()`](#adddata) method. In this method, you will pass your chosen custom bucketing key as a [`CustomData`](#customdata) object. Here, `newVisitorCode` refers to the identifier you wish to use for your bucketing (for example, the new `userId` or `accountId`).

<Warning>
  For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK's bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this [article](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/create-a-feature-flag#Advanced_Flag_Settings).
</Warning>

* **Bucketing logic:** Once a custom bucketing key is provided through the `AddData()` method, all hash calculations for assigning users to variations will use this `newVisitorCode` (your custom key) instead of the default `visitorCode`. Using the `newVisitorCode` means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
* **Data tracking and analytics:** It's crucial to note that while the `newVisitorCode` (your custom key) is used for bucketing decisions, **all subsequent data (tracking events and conversions, for example) is sent and associated with the *original* `visitorCode`.** This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment's broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.

#### Technical requirements

To effectively use a custom bucketing key:

* The key must be a `string`.
* It must be unique for the entity you intend to bucket (for example, if using a `userId`, each user's ID should be unique).
* The key must be available to the SDK at the exact moment the feature flag decision is evaluated for that user or request.

### 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](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

You can also use your own [external data to target users](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-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.

```go theme={null}
import (
	"development.kameleoon.net/sdk/go-sdk/v3/logging"
)

// The `NONE` log level does not allow logging.
logging.SetLogLevel(logging.NONE)

// The `ERROR` log level only allows logging issues that may affect the SDK's primary behavior.
logging.SetLogLevel(logging.ERROR)

// The `WARNING` log level allows logging issues which may require additional 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 logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
logging.SetLogLevel(logging.INFO)

// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
logging.SetLogLevel(logging.DEBUG)
```

#### Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

<Note>
  Logging limiting by a log level is performed apart from the log handling logic.
</Note>

```go theme={null}
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()

Call this method before any others to initialize the SDK. This method is in `KameleoonClientFactory`. This creates an instance of `KameleoonClient` to manage all interactions between the SDK and your app.

```go theme={null}
const siteCode = "sitecode"
config := &kameleoon.KameleoonClientConfig{
	// ...
}

client, err := KameleoonClientFactory.Create(siteCode, config)
```

##### Parameters

| Name                                                   | Type                    | Description                                                                                                                                                                    |
| ------------------------------------------------------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| siteCode <Badge color="red" size="sm">required</Badge> | string                  | This is a [unique key](/user-manual/faq#how-do-i-find-my-sitecode) of the Kameleoon project you are using with the SDK.                                                        |
| cfg <Badge color="red" size="sm">required</Badge>      | \*KameleoonClientConfig | Represents either the path to the SDK configuration file or the configuration object. If you provide the configuration object, it must contain the correct configuration keys. |

##### 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()

Call this method before any others to initialize the SDK. This method is in `KameleoonClientFactory`. This creates an instance of `KameleoonClient` to manage all interactions between the SDK and your app.

```go theme={null}
const siteCode = "sitecode"
client, err := KameleoonClientFactory.CreateFromFile(siteCode, "/etc/kameleoon/client-go.yaml")
```

###### Parameters

| Name                                                   | Type   | Description                                                                                                                                                     |
| ------------------------------------------------------ | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| siteCode <Badge color="red" size="sm">required</Badge> | string | A Kameleoon **siteCode**.                                                                                                                                       |
| cfgPath  <Badge color="red" size="sm">required</Badge> | 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**. |

###### 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.

```go theme={null}
const siteCode = "sitecode"
KameleoonClientFactory.Forget(siteCode)
```

###### Parameters

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

The `WaitInit` method of the `kameleoon.KameleoonClient` allows you to wait until the `KameleoonClient` instance is ready for use.

```go theme={null}
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)*

Use this method 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 [`GetVariation`](#getvariation) 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.
</Note>

If you specify a `visitorCode`, the `IsFeatureActive` method uses it as the unique visitor identifier, which is useful for [cross-device experimentation](/developer-docs/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.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.
</Note>

<Note>
  Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as `IsFeatureActive()`, `GetVariation()` or `GetVariations()`.

  Use the default `true` value for the `GetVariationOptParams.Track` parameter when you expose visitors to a variation and need to count them. Set the `GetVariationOptParams.Track` parameter to `false` only if you call these methods before you expose visitors.

  For example, if you call `GetVariations()` to retrieve all variations before you expose visitors, set the `GetVariationsOptParams.Track` parameter to `false`. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.

  Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
</Note>

```go theme={null}
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
}
```

<Warning>
  The `IsFeatureActive()` method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the **Then, for everyone else serve** default state. If you select **Off** for this default state, the method always returns `false` even when the master feature flag is **On**.
</Warning>

##### Parameters

| 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](/developer-docs/feature-experimentation/technical-reference/technical-considerations#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 `GetVariationOptParams.Track` parameter)*

Retrieves the [`Variation`](#variation) assigned to a given visitor for a specific feature flag.

This method takes a `visitorCode` and `featureKey` as mandatory arguments. The `GetVariationOptParams.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.

<Note>
  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.
</Note>

```go theme={null}
const featureKey = "new_checkout"

variation, err := client.GetVariation(visitorCode, featureKey)
// disabling tracking
variation, err := client.GetVariation(visitorCode, featureKey, 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
}
```

##### Parameters

| Name                                                                          | Type     | Description                                                                    | Default |
| ----------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------ | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge>                   | `string` | Unique identifier of the visitor.                                              |         |
| `featureKey` <Badge color="red" size="sm">required</Badge>                    | `string` | Key of the feature you want to expose to a visitor.                            |         |
| `GetVariationOptParams.Track` <Badge color="green" size="sm">optional</Badge> | `bool`   | An optional parameter to enable or disable tracking of the feature evaluation. | `true`  |

##### Return value

| Type        | Description                                                                                                          |
| ----------- | -------------------------------------------------------------------------------------------------------------------- |
| `Variation` | An assigned [`Variation`](#variation) to a given visitor for a specific feature flag on success, otherwise an error. |

##### 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 in the 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 `GetVariationsOptParams.Track` parameter)*

Retrieves a map of [`Variation`](#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 `GetVariationsOptParams.OnlyActive` and `GetVariationsOptParams.Track` are optional.

* If `GetVariationsOptParams.OnlyActive` is set to `true`, the method `GetVariations()` will return feature flags variations provided the user is not bucketed with the `off` variation.
* The `GetVariationsOptParams.Track` parameter controls whether or not the method will track the variation assignments. By default, it is set to `true`. If set to `false`, 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.

<Note>
  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.
</Note>

```go theme={null}
variations, err := client.GetVariations(visitorCode)
// all active variations
variations, err := client.GetVariations(visitorCode, NewGetVariationsOptParams().OnlyActive(true))
// disable tracking
variations, err := client.GetVariations(visitorCode, NewGetVariationsOptParams().Track(false))

if err != nil {
	// handle error
}
```

##### Parameters

| Name                                                                                | Type     | Description                                                                                                       | Default |
| ----------------------------------------------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge>                         | `string` | Unique identifier of the visitor.                                                                                 |         |
| `GetVariationsOptParams.OnlyActive` <Badge color="green" size="sm">optional</Badge> | `bool`   | An optional parameter indicating whether to return variations for active (`true`) or all (`false`) feature flags. | `false` |
| `GetVariationsOptParams.Track` <Badge color="green" size="sm">optional</Badge>      | `bool`   | 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`](#variation) objects of the feature flags using the keys of the corresponding features on success, otherwise an error. |

##### 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. |

##### Parameters

| 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`](#variation) 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. |

#### SetForcedVariation()

The method allows you to programmatically assign a specific [`Variation`](#variation) to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing.

When a **forced** variation is set, it overrides Kameleoon's real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set `SetForcedVariationOptParams.ForceTargeting=false` instead.

<Info>
  **Simulated** variations always take precedence in the execution order. If a **simulated** variation calculation is triggered, it will be fully processed and completed first.
</Info>

A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.

The method may throw exceptions under certain conditions (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.

<Warning>
  It’s important to distinguish **forced** variations from **[simulated](#getvisitorcode)** variations:

  * **Forced variations**: Are specific to an individual experiment.
  * **Simulated variations**: Affect the overall **feature flag** result.
</Warning>

```go theme={null}
const experimentId = 9516

// Forcing the variation "on" in the experiment 9516 for the visitor.
err := client.SetForcedVariation(visitorCode, experimentId, "on")

// Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment.
err := client.SetForcedVariation(
    visitorCode, experimentId, "on", NewSetForcedVariationOptParams().ForceTargeting(false),
)

// Resetting the forced variation in the experiment 9516 for the visitor.
err := client.SetForcedVariation(visitorCode, experimentId, "")

if err != nil {
    // Handling the error
}
```

##### Parameters

| Name                                                                                         | Type     | Description                                                                                                                                                                | Default |
| -------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge>                                  | `string` | Unique identifier of the visitor.                                                                                                                                          |         |
| `experimentId` <Badge color="red" size="sm">required</Badge>                                 | `int`    | **Experiment Id** that will be targeted and selected during the evaluation process.                                                                                        |         |
| `variationKey` <Badge color="red" size="sm">required</Badge>                                 | `string` | **Variation Key** corresponding to a `Variation` that should be forced as the returned value for the experiment. If the value is `""`, the forced variation will be reset. |         |
| `SetForcedVariationOptParams.ForceTargeting` <Badge color="green" size="sm">optional</Badge> | `bool`   | Indicates whether targeting for the experiment should be forced and skipped (`true`) or applied as in the standard evaluation process (`false`).                           | `true`  |

##### 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.FeatureExperimentNotFound` | Exception indicating that the requested experiment id has not been found in the SDK's internal configuration. This is usually normal and means that the rule's corresponding experiment has not yet been activated on Kameleoon's side.               |
| `errs.FeatureVariationNotFound`  | Exception indicating that the requested variation key(id) has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |

#### EvaluateAudiences()

* 📨 *Sends Tracking Data to Kameleoon*

This method evaluates visitors against all available Audiences Explorer segments and tracks those who match.

`EvaluateAudiences()` should be called **after all relevant visitor data has been set or updated**, and **just before** getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria.

After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.

```go theme={null}
if err := client.EvaluateAudiences(visitorCode); err != nil {
    // Handling the error
}
```

##### Parameters

| Name                                                        | Type     | Description                       |
| ----------------------------------------------------------- | -------- | --------------------------------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string` | Unique identifier of the visitor. |

##### 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. |

#### GetDataFile()

<Tip>
  To evaluate all feature flags, use [`GetVariations()`](#getvariations). This method is more efficient than calling `DataFile` and iterating through flags with [`GetVariation()`](#getvariation).
</Tip>

Returns the current SDK configuration as a [`DataFile`](#datafile) object.

```go theme={null}
dataFile := client.GetDataFile()
```

##### Return value

| Type       | Description                                                  |
| ---------- | ------------------------------------------------------------ |
| `DataFile` | The [`DataFile`](#datafile) containing the SDK configuration |

### Visitor data

#### GetVisitorCode()

<Note>
  This method was previously called `ObtainVisitorCode`, which was removed in SDK version `3.0.0`.
</Note>

To ensure user identification consistency, especially when using Kameleoon in [hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/), you should call the [`GetVisitorCode()`](#getvisitorcode) method to obtain the Kameleoon `visitorCode` for the current visitor. Here's how it works:

1. Kameleoon checks if there is a **kameleoonVisitorCode** cookie associated with the current HTTP request. If found, Kameleoon this code 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 identifiers as visitor codes allows you to match Kameleoon visitors with your own users without additional look-ups.

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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation).

<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.
</Note>

<Info>
  The `GetVisitorCode()` method allows you to set **simulated** variations for a visitor. When cookies (from a **request** or **document**) contain the key `kameleoonSimulationFFData`, the standard evaluation process is bypassed. Instead, the method directly returns a [`Variation`](#variation) based on the provided data.

  You can apply simulations in two ways:

  * **Automatically (recommended):** If using Kameleoon Web Experimentation or the SDK in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation#linking-feature-experiments-with-front-end-tracking-code), the cookie is created automatically when simulating a variant's display using the [Simulation Panel](/user-manual/experimentation/feature-experimentation/using-the-rollout-planner/validation-and-rollback/using-simulation-mode).
  * **Manually:** Set the `kameleoonSimulationFFData` cookie manually.

  It’s important to distinguish **simulated** variations from **[forced](#setforcedvariation)** variations:

  * **Simulated variations**: Affect the overall **feature flag** result.
  * **Forced variations**: Are specific to an individual experiment.

  ⚙️ **Manual setup**

  Please ensure the `kameleoonSimulationFFData` cookie follows this format:

  * `kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}`: Simulates the variation with `varId` of experiment `expId` for the given `featureKey`.
  * `kameleoonSimulationFFData={"featureKey":{"expId":0}}`: Simulates the default variation (defined in the **Then, for everyone else in Production, serve** section) for the given `featureKey`.

  ⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).
</Info>

```go theme={null}
visitorCode, err := client.GetVisitorCode(req, resp)

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

##### Parameters

| 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](#data-types) 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*()`](#flushall--flushvisitor--flushvisitorinstantly) method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered by the `Flush*()`.

The [`TrackConversion()`](#trackconversion) method also sends out any previously associated data, just like the `Flush*()`. The same holds true for [`GetVariation()`](#getvariation) and [`GetVariations()`](#getvariations) methods if an experimentation rule is triggered.

<Tip>
  Each visitor can only have one instance of associated data for most data types. However, [`CustomData`](#customdata) is an exception. Visitors can have one instance of associated `CustomData` per index.
</Tip>

```go theme={null}
import (
	"github.com/Kameleoon/client-go/v3/types"
)
// Add a single data item (tracked by default)
client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeChrome))

// Add multiple data items (tracked by default)
client.AddData(visitorCode,
    types.NewPageViewWithTitle("https://url.com", "title", 3),
    types.UserAgent("UserAgent"),
)

// Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
client.AddDataWithOptParams(
    visitorCode,
    NewAddDataOptParams().Track(false),
    types.NewPageViewWithTitle("https://url.com", "title", 3),
    types.UserAgent("UserAgent")
)
```

##### Parameters

| Name                                                        | Type            | Description                                                                                                                                                                                  | Default value |
| ----------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string`        | Unique identifier of the visitor.                                                                                                                                                            |               |
| `track` <Badge color="green" size="sm">optional</Badge>     | `bool`          | Specifies whether the added data is eligible for tracking. When set to `false`, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | `true`        |
| `allData` <Badge color="red" size="sm">required</Badge>     | `...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*

The `FlushAll()/FlushVisitor()/FlushVisitorInstantly()` methods collects the Kameleoon data linked to the visitor. It then sends a tracking request, along with all data added using the `AddData` method, which has not yet been sent using one of [these methods](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics). `Flush*()` is non-blocking as the server call is made asynchronously.

`Flush*()` lets you 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](/developer-docs/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.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.
</Note>

```go theme={null}
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 tracking method)
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 a unique ID
client.AddData(types.NewUniqueIdentifier(true))
client.FlushVisitor(visitorCode)
```

##### Parameters

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

#### 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 User ID.

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 all 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.

```go theme={null}
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.
</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 Visitor code or your User ID. You can refer to the sample code provided below to retrieve and utilize Mixpanel cohorts:

```go theme={null}
//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...))
}
```

##### Parameters

| 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](#initialization). |

##### 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](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation) for a better understanding of possible use cases.

<Warning>
  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 `AddData()` method. It is particularly useful for [synchronizing custom data between multiple devices](/developer-docs/sdks/web-sdks/nodejs-sdk#synchronizing-custom-data-across-devices).
</Warning>

<Note>
  The parameter `IsUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.
</Note>

```go theme={null}
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 a unique ID
client.AddData(types.NewUniqueIdentifier(true))
visitorData, err = client.GetRemoteVisitorData(visitorCode, true)

// If you want to fetch a 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
)
```

##### Parameters 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](#initialization). |

##### Parameters 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](#initialization). |

##### Parameters of GetRemoteVisitorDataWithOptParams

<Note>
  The `GetRemoteVisitorDataWithOptParams` method is deprecated. Please use [`GetRemoteVisitorDataWithFilter`](/developer-docs/sdks/web-sdks/go-sdk#arguments-of-getremotevisitordatawithfilter) and [`UniqueIdentifier`](#uniqueidentifier). instead.
</Note>

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

<Note>
  Here is the list of `kameleoon.RemoteVisitorDataOptParams` fields:

  | Name                                                                            | Type            | Description                                                                                                                                                                                                                                                          |
  | ------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | IsUniqueIdentifier <Badge color="green" size="sm">optional</Badge> (Deprecated) | `bool`          | A parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is `false`.                                                                                                                                                 |
  | Timeout <Badge color="green" size="sm">optional</Badge>                         | `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](#initialization). |

  The default value of `kameleoon.RemoteVisitorDataOptParams` which is `types.RemoteVisitorDataFilter{PreviousVisitAmount: 1, CurrentVisit: true, CustomData: true}`, can be gotten with `types.DefaultRemoteVisitorDataFilter()` function.
</Note>

##### Return value

| Type          | Description                                    |
| ------------- | ---------------------------------------------- |
| \[]types.Data | A slice of data assigned to the given visitor. |
| error         | An occurred error.                             |

##### 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.

<Note>
  Here is the list of available `types.RemoteVisitorDataFilter` options:

  | Name                                                                | Type   | Description                                                                                                                                                                                                                                                                                                                                     | Default |
  | ------------------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
  | PreviousVisitAmount <Badge color="green" size="sm">optional</Badge> | `int`  | Number of previous visits to retrieve data from. Number between `1` and `25`                                                                                                                                                                                                                                                                    | `1`     |
  | CurrentVisit <Badge color="green" size="sm">optional</Badge>        | `bool` | If true, current visit data will be retrieved                                                                                                                                                                                                                                                                                                   | `true`  |
  | CustomData <Badge color="green" size="sm">optional</Badge>          | `bool` | If true, custom data will be retrieved.                                                                                                                                                                                                                                                                                                         | `true`  |
  | PageViews <Badge color="green" size="sm">optional</Badge>           | `bool` | If true, page data will be retrieved.                                                                                                                                                                                                                                                                                                           | `false` |
  | Geolocation <Badge color="green" size="sm">optional</Badge>         | `bool` | If true, geolocation data will be retrieved.                                                                                                                                                                                                                                                                                                    | `false` |
  | Device <Badge color="green" size="sm">optional</Badge>              | `bool` | If true, device data will be retrieved.                                                                                                                                                                                                                                                                                                         | `false` |
  | Browser <Badge color="green" size="sm">optional</Badge>             | `bool` | If true, browser data will be retrieved.                                                                                                                                                                                                                                                                                                        | `false` |
  | OperatingSystem <Badge color="green" size="sm">optional</Badge>     | `bool` | If true, operating system data will be retrieved.                                                                                                                                                                                                                                                                                               | `false` |
  | Conversions <Badge color="green" size="sm">optional</Badge>         | `bool` | If true, conversion data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | Experiments <Badge color="green" size="sm">optional</Badge>         | `bool` | If true, experiment data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | Kcs <Badge color="green" size="sm">optional</Badge>                 | `bool` | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the [AI Predictive Targeting add-on](/user-manual/assets/segments/target-users-based-on-likelihood-to-convert)                                                                                                                                                            | `false` |
  | VisitorCode <Badge color="green" size="sm">optional</Badge>         | `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 variation across visits for [Cross-device experimentation](/developer-docs/cross-device-experimentation). | `true`  |
  | Personalization <Badge color="green" size="sm">optional</Badge>     | `bool` | If true, personalization data will be retrieved. This is required for the personalization condition.                                                                                                                                                                                                                                            | `false` |
  | cbs <Badge color="green" size="sm">optional</Badge>                 | `bool` | If true, Contextual Bandit score data will be retrieved.                                                                                                                                                                                                                                                                                        | `false` |
</Note>

#### 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](/user-manual/integrations/data-warehouses/bigquery/use-bigquery-as-a-source-audience-targeting) 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.

```go theme={null}
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})
```

##### Parameters 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](#initialization). This field is optional. |

##### Parameters 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.                                                                                    |

<Note>
  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. |
</Note>

<Note>
  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`.
</Note>

##### Return value

| Type               | Description                                                                     |
| ------------------ | ------------------------------------------------------------------------------- |
| \*types.CustomData | A `CustomData` instance confirming that the data has been added to the visitor. |
| error              | An occurred error.                                                              |

#### 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 method 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](/user-manual/project-management/consent-management-policy).

```go theme={null}
visitorCode, err := kameleoonClient.GetVisitorCode(req, resp)

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

##### Parameters

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

##### Consent revocation behavior

When you call `SetLegalConsent()` with `consent=false`, the SDK does not delete the `kameleoonVisitorCode` cookie. Instead, it stops extending the cookie's expiration date, allowing the cookie to persist until it naturally expires.

If your compliance requirements demand the immediate removal of the cookie file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK will not remove the file automatically.

### Goals and third-party analytics

#### TrackConversion()

* 📨 *Sends Tracking Data to Kameleoon*

Use this method to track a conversion for a specific [goal](/user-manual/assets/goals/create-a-goal) and user. This method requires `visitorCode` and `goalId`. In addition, this method also accepts an optional `TrackConversionOptParams.Revenue`, `TrackConversionOptParams.Negative` and `TrackConversionOptParams.Metadata` arguments. The `visitorCode` is usually identical to the one that was used when triggering the experiment.

The `TrackConversion()` method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#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.
</Note>

```go theme={null}
import (
	"github.com/Kameleoon/client-go/v3/types"
)

const goalID = 83023

client.TrackConversion(visitorCode, goalID)

client.TrackConversionRevenue(visitorCode, goalID, 10.0)

// Add metadata
client.TrackConversionWithOptParams(visitorCode, goalID, TrackConversionOptParams{
    Metadata: []*types.CustomData{
        types.NewCustomData(3, "metadata1", "md2"),
        types.NewCustomData(5, "md3")
    },
})
```

##### Parameters

| Name                                                                                | Type            | Description                                                                                                                                                                                                                                                                                                                          | Default |
| ----------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge>                         | `string`        | Unique identifier of the visitor.                                                                                                                                                                                                                                                                                                    |         |
| `goalId` <Badge color="red" size="sm">required</Badge>                              | `int`           | ID of the goal.                                                                                                                                                                                                                                                                                                                      |         |
| `TrackConversionOptParams.Revenue` <Badge color="green" size="sm">optional</Badge>  | `float64`       | Revenue of the conversion.                                                                                                                                                                                                                                                                                                           | `0`     |
| `TrackConversionOptParams.Negative` <Badge color="green" size="sm">optional</Badge> | `bool`          | Defines if the revenue is positive or negative.                                                                                                                                                                                                                                                                                      | `false` |
| `TrackConversionOptParams.Metadata` <Badge color="green" size="sm">optional</Badge> | `[]*CustomData` | Lets you set specific values for custom data which have been defined as metadata for the goal in the Kameleoon App. Example: `[CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]`. In this example, `5` and `6` are the indexes of the custom data (5 = “Payment Type”, 6 = “Delivery Method”). | `nil`   |
| `isUniqueIdentifier` *(deprecated)*                                                 | `bool`          | An optional parameter for specifying if the visitorCode is a unique identifier.                                                                                                                                                                                                                                                      | `false` |

<Note>
  TrackConversionOptParams.Metadata values are accessible through [raw data exports](/user-manual/experiment-analytics/analyze-results/results-page-actions#Export) and [the results page](/user-manual/experiment-analytics/analyze-results/goal-metadata).

  If the `TrackConversionOptParams.Metadata` parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the [`AddData()`](#adddata) method. If the parameter is omitted, Kameleoon will use the last tracked values for those [`CustomData`](#customdata) prior to the conversion and within the same visit.

  Kameleoon will only consider the metadata values that are explicitly passed as parameters to the `TrackConversion()` method.

  In the example below, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value 'Amex Credit Card').

  ```go theme={null}
  kameleoonClient.AddData(visitorCode, types.NewCustomData(5, "Credit Card"), types.NewCustomData(9, "Express Delivery"));
  kameleoonClient.TrackConversionWithOptParams(visitorCode, 10, TrackConversionOptParams{
      Metadata: []*types.CustomData{
          types.NewCustomData(9, "Amex Credit Card"),
      },
  })
  ```
</Note>

##### Exceptions

| Type                      | Description                                                                                                         |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `errs.VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### GetEngineTrackingCode()

Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the `GetEngineTrackingCode()` method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.

Refer to [hybrid experimentation](/developer-docs/feature-experimentation/get-started/hybrid-experimentation) for more information on implementing this method.

```go theme={null}
engineTrackingCode := kameleoonClient.GetEngineTrackingCode(visitorCode)
```

<Note>
  * To use this feature, implement both the Go SDK and Kameleoon [Engine.js](/developer-docs/web-experimentation/implementation-and-deployment/standard-implementation). Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing `</body>` tag.
  * If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the [JavaScript / TypeScript SDK](/developer-docs/sdks/web-sdks/js-sdk). This option works well for [serverless edge compute platforms](/developer-docs/feature-experimentation/implementation-and-deployment/serverless-edge-compute-starter-kits). The JavaScript / TypeScript SDK automatically tracks variations when you call [`getVisitorCode`](/developer-docs/sdks/web-sdks/js-sdk#getvisitorcode), as long as you add the corresponding experiment assignments to `window.kameleoonQueue`.
  * You can insert the returned tracking code directly into an HTML `<script>` tag.

  ```html theme={null}
  <html lang="en">
    <body>
      <script>
        const engineTrackingCode = `
          window.kameleoonQueue = window.kameleoonQueue || [];
          window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
          window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
        `;
        const script = document.createElement('script');

        script.textContent = engineTrackingCode;
        document.body.appendChild(script);
      </script>

    </body>
  </html>
  ```

  In this example, `123456` and `234567` are experiment IDs, and `7890` and `8901` are variation IDs. In your implementation, the SDK generates these values in the returned tracking code.
</Note>

##### Parameters

| Name                                                        | Type     | Description                       |
| ----------------------------------------------------------- | -------- | --------------------------------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string` | Unique identifier of the visitor. |

##### Return value

| Type     | Description                              |
| -------- | ---------------------------------------- |
| `string` | JavaScript code to insert into the page. |

### Events

#### OnUpdateConfiguration()

```go theme={null}
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.

##### Parameters

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

| Name                                                        | Type          | Description                                                                                                                                |
| ----------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `browserType` <Badge color="red" size="sm">required</Badge> | `BrowserType` | List of browsers: `BrowserTypeChrome`, `BrowserTypeIE`, `BrowserTypeFirefox`, `BrowserTypeSafari`, `BrowserTypeOpera`, `BrowserTypeOther`. |
| `version` <Badge color="green" size="sm">optional</Badge>   | `float32`     | Version of the browser, floating point number represents major and minor version of the browser                                            |

```go theme={null}
client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeChrome))

client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeSafari, 16.0))
```

#### Conversion

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

<Tip>
  * Each visitor can have multiple `Conversion` objects.
  * You can find the `goalId` in the Kameleoon app.
</Tip>

| Name                                                                           | Type                  | Description                                     | Default |
| ------------------------------------------------------------------------------ | --------------------- | ----------------------------------------------- | ------- |
| `goalId` <Badge color="red" size="sm">required</Badge>                         | `int`                 | ID of the goal.                                 |         |
| `ConversionOptParams.Revenue` <Badge color="green" size="sm">optional</Badge>  | `float64`             | Revenue of the conversion                       | `0`     |
| `ConversionOptParams.Negative` <Badge color="green" size="sm">optional</Badge> | `bool`                | Defines if the revenue is positive or negative. | `false` |
| `ConversionOptParams.Metadata` <Badge color="green" size="sm">optional</Badge> | `[]*types.CustomData` | Metadata of the conversion.                     | `nil`   |

```go theme={null}
client.AddData(visitorCode, types.NewConversion(32, true))

client.AddData(visitorCode, types.NewConversionWithRevenue(33, 10.0, false))

client.AddData(
    visitorCode,
    types.NewConversionWithOptParams(34, types.ConversionOptParams{
        Revenue: 5.0,
        Metadata: []*types.CustomData{
            types.NewCustomData(3, "metadata1", "md2"),
            types.NewCustomData(5, "md3"),
        },
    }),
)
```

```go theme={null}
client.AddData(visitorCode, types.NewConversion(32, false))

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

#### Cookie

`Cookie` contains information about the cookie stored on the visitor's device.

| Name    | Type                | Description                                                                       |
| ------- | ------------------- | --------------------------------------------------------------------------------- |
| cookies | `map[string]string` | A string object map consisting of cookie keys and values. This field is required. |

<Tip>
  Each visitor can only have one `Cookie`. Adding second `Cookie` overwrites the first one.
</Tip>

```go theme={null}
cookie := types.NewCookie(map[string]string{
  "k1": "v1",
  "k2": "v2",
})
client.AddData(visitorCode, cookie)
```

#### Geolocation

`Geolocation` contains the visitor's geolocation details.

| Name                                                         | Type                  | Description                                                                                                      |
| ------------------------------------------------------------ | --------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `country` <Badge color="red" size="sm">required</Badge>      | `string`              | The country of the visitor.                                                                                      |
| `region` <Badge color="green" size="sm">optional</Badge>     | <nobr>`string`</nobr> | The region of the visitor.                                                                                       |
| `city` <Badge color="green" size="sm">optional</Badge>       | <nobr>`string`</nobr> | The city of the visitor.                                                                                         |
| `postalCode` <Badge color="green" size="sm">optional</Badge> | <nobr>`string`</nobr> | The postal code of the visitor.                                                                                  |
| `latitude` <Badge color="green" size="sm">optional</Badge>   | `float64`             | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.  |
| `longitude` <Badge color="green" size="sm">optional</Badge>  | `float64`             | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |

<Tip>
  * Each visitor can have only one `Geolocation`. Adding a second `Geolocation` overwrites the first one.
</Tip>

```go theme={null}
client.AddData(visitorCode, types.NewGeolocation("France", "Île-de-France", "Paris"))

client.AddData(visitorCode, types.NewGeolocationWithCoords(48.856667, 2.352222, "France", "Île-de-France", "Paris"))
```

#### CustomData

`CustomData` allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in [segments](/user-manual/assets/segments/create-a-segment/) or as a filter/breakdown in experiment reports. To learn more about custom data, please refer to this [article](/developer-docs/custom-data).

| Name                                                      | Type           | Description                                                                                                                                                                             | Default |
| --------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| index/name <Badge color="red" size="sm">required</Badge>  | `int`/`string` | Index or Name of the custom data. **Either `index` or `name` must be provided** to identify the data.                                                                                   |         |
| values <Badge color="red" size="sm">required</Badge>      | `...string`    | The values of the custom data to be stored.                                                                                                                                             |         |
| overwrite <Badge color="green" size="sm">optional</Badge> | `bool`         | Flag to explicitly control how the values are stored and how they appear in reports. [See more](/developer-docs/custom-data#default-logic-when-overwrite-parameter-is-false-or-omitted) | `true`  |

```go theme={null}
client.AddData(visitorCode, types.NewCustomData(1, "value"))

// With several values
client.AddData(visitorCode, types.NewCustomData(1, "value1", "value2"))

// To set the 'overwrite' flag to false
client.AddData(
    visitorCode,
    types.NewCustomDataWithOptParams(1, NewCustomDataOptParams().Overwrite(false), "value"),
)

// To use a name instead of the index
client.AddData(visitorCode, types.NewNamedCustomData("my-custom-data", "value"))

// To use a name instead of the index
// and set the 'overwrite' flag to false
client.AddData(
    visitorCode,
    types.NewNamedCustomDataWithOptParams("my-custom-data", NewCustomDataOptParams().Overwrite(false), "value"),
)
```

<Note>
  * Each visitor is allowed only one `CustomData` for each unique `index`. Adding another `CustomData` with the same `index` will replace the existing one.

  * The custom data ‘index’ can be found in the [Custom Data dashboard](/user-manual/assets/custom-data/manage-custom-data) under the “INDEX” column.

  * To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: **Use this data only locally for targeting purposes** when creating custom data.

  * Adding a `CustomData` instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
</Note>

#### Device

You can use device data to filter experiment or personalization reports by any associated value.

###### NewDevice

| Name       | Type       | Description                                                                   |
| ---------- | ---------- | ----------------------------------------------------------------------------- |
| deviceType | DeviceType | List of devices: **Phone**, **Tablet**, **Desktop**. This field is mandatory. |

```go theme={null}
client.AddData(visitorCode, types.NewDevice(types.DeviceTypeDesktop))
```

#### OperatingSystem

`OperatingSystem` contains information about the operating system on the visitor's device.

##### NewOperatingSystem

| Name | Type                        | Description                                                                                                                    |
| ---- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| type | `types.OperatingSystemType` | List of operating systems: **Windows**, **Mac**, **iOS**, **Linux**, **Android** and **WindowsPhone**. This field is required. |

<Tip>
  Each visitor can only have one `OperatingSystem`. Adding a second `OperatingSystem` overwrites the first one.
</Tip>

```go theme={null}
client.AddData(visitorCode, types.NewOperatingSystem(types.OperatingSystemTypeWindows))
```

#### PageView

You can use pageview data to filter experiment or personalization reports by any associated value.

<Note>
  The index or ID of the [referrer](/user-manual/assets/advanced-targeting-tools/create-an-acquisition-channel) can be found in your Kameleoon account. It is important to note that this index starts at 0. This means the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.
</Note>

##### 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. |

```go theme={null}
client.AddData(visitorCode, types.NewPageView("https://url.com", 3))

client.AddData(visitorCode, types.NewPageViewWithTitle("https://url.com", "title", 3))
```

#### UserAgent

Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to tackle this issue and recognize known bots and spiders. Kameleoon also uses the `UserAgent` field to filter out bots and other unwanted traffic that might distort your conversion metrics. For more details, see our help article on [bot filtering](/user-manual/faq#how-does-kameleoon-filter-bot-traffic-from-my-results).

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

##### NewUserAgent

| Name  | Type   | Description                                                                             |
| ----- | ------ | --------------------------------------------------------------------------------------- |
| value | string | The User-Agent value that will be sent with tracking requests. This field is mandatory. |

```go theme={null}
client.AddData(visitorCode, types.NewUserAgent("visitor_user_agent"))
```

#### 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](/developer-docs/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 `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.

##### NewUniqueIdentifier

| Name  | Type | Description                                                                                    |
| ----- | ---- | ---------------------------------------------------------------------------------------------- |
| value | bool | Parameter for specifying if the visitor\_code is a unique identifier. This field is mandatory. |

```go theme={null}
client.AddData(visitorCode, types.NewUniqueIdentifier(true))
```

#### ApplicationVersion

`ApplicationVersion` represents the semantic version number of your application.

<Tip>
  A **visitor** can have only one `ApplicationVersion`. Adding a second instance will overwrite the first one.
</Tip>

##### NewApplicationVersion

| Name                                                    | Type     | Description                                                                                                                                      |
| ------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| version <Badge color="green" size="sm">optional</Badge> | `string` | The mobile application version. This field must follow semantic versioning. Accepted formats are `major`, `major.minor`, or `major.minor.patch`. |

```go theme={null}
client.AddData(visitorCode, types.NewApplicationVersion("10")) // major

client.AddData(visitorCode, types.NewApplicationVersion("10.20")) // major.minor

client.AddData(visitorCode, types.NewApplicationVersion("10.20.30")) // major.minor.patch
```

### Returned Types

#### DataFile

The `DataFile` contains the SDK configuration details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name           | Type                     | Description                                                                       |
| -------------- | ------------------------ | --------------------------------------------------------------------------------- |
| `FeatureFlags` | `map[string]FeatureFlag` | A map of [`FeatureFlag`](#featureflag) objects, keyed by feature flag keys.       |
| `DateModified` | `int64`                  | The timestamp (in milliseconds) indicating when the `DataFile` was last modified. |

```go theme={null}
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
featureFlags := dataFile.FeatureFlags

// Retrieves the last modification timestamp of the DataFile.
// The value is an int64 representing milliseconds since the Unix epoch.
dateModified := dataFile.DateModified
```

#### FeatureFlag

The `FeatureFlag` represents a set of properties that define a feature flag itself — for example, its [`Variations`](#variation), [`Rules`](#rule), environment status, and other related details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name                   | Type                   | Description                                                                |
| ---------------------- | ---------------------- | -------------------------------------------------------------------------- |
| `IsEnvironmentEnabled` | `bool`                 | Indicating whether the feature flag is enabled in the current environment. |
| `DefaultVariationKey`  | `string`               | The key of the default variation associated with the feature flag.         |
| `Variations`           | `map[string]Variation` | A map of `Variation` objects, keyed by variation keys.                     |
| `Rules`                | `[]Rule`               | A list of `Rule` objects                                                   |

```go theme={null}
// Check whether the feature flag is enabled in the current environment
isEnvironmentEnabled := featureFlag.IsEnvironmentEnabled

// Retrieve the key of the default variation
defaultVariationKey = featureFlag.DefaultVariationKey

// Retrieve the default variation object
defaultVariation := featureFlag.DefaultVariation()

// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
variations := featureFlag.Variations

// Retrieve all targeting rules associated with the feature flag
rules := featureFlag.Rules
```

#### Rule

The `Rule` represents a set of properties that define a rule itself — for example, its [`Variations`](#variation).

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name         | Type                   | Description                                            |
| ------------ | ---------------------- | ------------------------------------------------------ |
| `Variations` | `map[string]Variation` | A map of `Variation` objects, keyed by variation keys. |

```go theme={null}
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
variations := rule.Variations
```

#### Variation

`Variation` contains information about the visitor's assigned variation (or the default variation, if no specific assignment exists).

| Name         | Type                  | Description                                                                                                                                          |
| ------------ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| Name         | `string`              | The name of the variation.                                                                                                                           |
| 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. |

<Note>
  * The `Variation` object provides details about the assigned variation and its associated experiment, while the [`Variable`](#variable) object contains specific details about each variable within a variation.
  * Ensure that your code handles the case where `VariationID` or `ExperimentID` may be `nil`, indicating a default variation.
  * The `Variables` map might be empty if no variables are associated with the variation.
</Note>

```go theme={null}
// Retrieving the variation name
var variationName string = variation.Name

// 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**. |

```go theme={null}
// 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)
```

### Deprecated methods

<Warning>
  These methods are deprecated and will be removed in SDK version `4.0.0`.
</Warning>

#### GetFeatureVariationKey()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  Use [`GetVariation()`](#getvariation) instead.
</Note>

This method retrieves the configuration of a [feature experiment](/user-manual/experimentation/feature-experimentation/using-the-rollout-planner/optimizations-and-scheduling/create-feature-experiments) 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. See the example code for guidance.
</Note>

If you specify a `visitorCode`, the `GetFeatureVariationKey` method uses it as the unique visitor identifier, which is useful for [cross-device experimentation](/developer-docs/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.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.
</Note>

```go theme={null}
// 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.
}
```

##### Parameters

| 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](/developer-docs/feature-experimentation/technical-reference/technical-considerations#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()

<Note>
  Use [`GetActiveFeatures()`](#getactivefeatures) instead.
</Note>

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 available for that `visitorCode`.

Don't forget to handle potential exceptions with proper error handling in your code. For example, see the following code:

```go theme={null}
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()

<Note>
  Use [`GetVariations()`](#getvariations) instead.
</Note>

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:

```go theme={null}
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. |

#### GetFeatureVariable()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  Use [`GetVariation()`](#getvariation) instead.
</Note>

To get a [feature variable](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/define-feature-variables) 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 returns 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. See the example code for guidance.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.
</Note>

```go theme={null}
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 on variableValue
} else {
	// An error occurred; the feature flag has not been found in the current configuration fetched by the SDK.
}
```

##### Parameters

| 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 SDK's internal configuration. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in [polling](/developer-docs/feature-experimentation/technical-reference/technical-considerations#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 SDK's internal configuration. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in [polling](/developer-docs/feature-experimentation/technical-reference/technical-considerations#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()

<Note>
  Use [`GetVariation()`](#getvariation) instead.
</Note>

To retrieve all variables associated with a feature flag, you must call the `GetFeatureVariationVariables` method. This method requires 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.

```go theme={null}
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
}
```

##### Parameters

| 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 SDK's internal configuration. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in [polling](/developer-docs/feature-experimentation/technical-reference/technical-considerations#polling) mode.   |
| errs.FeatureVariationNotFound   | This error indicates that the requested variation key could not be found in the SDK's internal configuration. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in [polling](/developer-docs/feature-experimentation/technical-reference/technical-considerations#polling) mode. |
| errs.FeatureEnvironmentDisabled | This error indicates that the feature flag is disabled for the current environment.                                                                                                                                                                                                                                                              |

#### GetFeatureList()

Returns a list of feature flag keys currently available for the SDK.

```go theme={null}
arrayFeatureKeys := client.GetFeatureList()
```

##### Return value

| Type       | Description               |
| ---------- | ------------------------- |
| `[]string` | List of feature flag keys |
