Con el SDK de Go de Kameleoon, puede ejecutar experimentos y activar feature flags. Integrar nuestro SDK en su aplicación web es sencillo y su huella (memoria y uso de red) es baja.
Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador.
Changelog: Última versión del SDK de Go: 3.18.0 Changelog.
Métodos del SDK: Para la documentación de referencia completa del SDK de Go, consulte la sección referencia.
Guía del desarrollador
Follow this section to install and configure the SDK, and learn about advanced features.
Primeros pasos
Instalación del cliente Go
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:
go get github.com/Kameleoon/client-go/v3
Configuración adicional
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.
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.
La versión actual del SDK de Go tiene las siguientes claves disponibles en el archivo de configuración:
| Clave | Descripción | Valor predeterminado |
|---|
ClientID / client_id (obligatorio) | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_id, consulte la documentación de credenciales de API. | |
ClientSecret / client_secret (obligatorio) | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_secret, consulte la documentación de credenciales de API. | |
SessionDuration / session_duration (opcional) | Designa el intervalo de tiempo predefinido durante el cual Kameleoon almacena al visitante y sus datos asociados en memoria (RAM). Tenga en cuenta que aumentar la duración de la sesión incrementa la cantidad de RAM que debe asignarse para almacenar los datos del visitante. | 30 minutos |
RefreshInterval / refresh_interval (opcional) | Especifica el intervalo de actualización, en minutos, con el que el SDK obtiene la configuración de los experimentos activos y los feature flags. El valor determina el tiempo máximo necesario para propagar los cambios, como activar o desactivar feature flags o lanzar experimentos, a sus servidores de producción. Adicionalmente, ofrecemos un modo streaming que utiliza server-sent events (SSE) para enviar nuevas configuraciones al SDK automáticamente y aplicar las nuevas configuraciones en tiempo real, sin ningún retraso. | 60 minutos |
DefaultTimeout / default_timeout (opcional) | Especifica el tiempo de espera, en milisegundos, para las solicitudes de red desde el SDK. Establezca el valor en 30 segundos o más si no dispone de una conexión estable. Algunos métodos tienen un parámetro adicional que puede utilizar para anular el tiempo de espera predeterminado para ese método en particular. Si no especifica el tiempo de espera para un método de forma explícita, el SDK utiliza este valor predeterminado. | 10000 milisegundos |
TrackingInterval / tracking_interval (opcional) | Especifica el intervalo para las solicitudes de seguimiento en milisegundos. Todos los visitantes que Kameleoon haya evaluado para cualquier feature flag o cuyos datos se hayan vaciado se incluyen en esta solicitud de seguimiento, que el SDK realiza una vez por intervalo. El valor mínimo es 1000 ms, que también es el predeterminado, y el valor máximo es 5000 ms. | 1000 milisegundos |
Environment / environment (opcional) | Entorno desde el cual se debe utilizar la configuración del feature flag. El valor puede ser production, staging o development. Consulte el artículo de gestión de entornos para más detalles. | production |
TopLevelDomain / top_level_domain (obligatorio en modo híbrido) | El dominio de nivel superior actual de su sitio web. Use el formato: example.com. No incluya https://, www ni otros subdominios. Kameleoon utiliza esta información para establecer la cookie correspondiente en el dominio de nivel superior. | "" |
ProxyUrl / proxy_url (opcional) | Establece el host proxy para todas las llamadas de salida al servidor realizadas por el SDK. | "" |
NetworkDomain / network_domain (opcional) | Dominio personalizado utilizado por los SDKs para las solicitudes salientes, a menudo para proxy. Debe ser un dominio válido (por ejemplo, example.com o sub.example.com). Los formatos no válidos se sustituyen por el valor de Kameleoon. | "" |
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 instead. | false |
To learn more about client_id and client_secret, and instructions on how to obtain them, please refer to this article. It’s worth noting that our Go SDK utilizes the Automation API and follows the OAuth 2.0 client credentials flow.
Initializing the Kameleoon Client
Once you have installed our SDK in your application, 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.
Puede personalizar el comportamiento del SDK (por ejemplo, el entorno o las credenciales) proporcionando un objeto de configuración.
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", // Este campo es obligatorio. Please enter your client_id here.
ClientSecret: "your-client-secret", // Este campo es obligatorio. 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")
Activación de un feature flag
Asignación de un ID único a un usuario
To assign a unique ID to a user, you can use the GetVisitorCode() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode that you would have generated. The ID is then set in a response headers cookie.
Si está usando Kameleoon en modo híbrido, llamar al método GetVisitorCode() garantiza que el ID único (visitor code) se comparta entre el archivo de aplicación engine.js (anteriormente llamado kameleoon.js) y el SDK.
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon.
To determine the status or variation of a feature flag for a specific user, you should use the GetVariation() or IsFeatureActive() method to retrieve the configuration based on the featureKey.
El método GetVariation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del featureKey y el visitorCode.
El método IsFeatureActive() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.
If your feature flag has associated variables (such as specific behaviors tied to each variation) GetVariation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When 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. De forma predeterminada, 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. Si desea saber más sobre how tracking works, view this article
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the AddData() method to add these data points to the user’s profile.
To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the 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.
Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema.
Además, los puntos de datos que añade al perfil del visitante estarán disponibles al analizar sus experimentos, lo que le permite filtrar y desglosar sus resultados por factores como el dispositivo y el navegador. El modo híbrido de Kameleoon recopila automáticamente una variedad de puntos de datos en el lado del cliente, lo que facilita desglosar sus resultados en función de estos puntos de datos previamente recopilados. Consulte la lista completa aquí.
Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método Flush*() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Para asegurarse de que sus resultados sean precisos, se recomienda filtrar los bots utilizando el tipo de dato UserAgent.
Tracking flag exposition and goal conversions
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el método TrackConversion() y proporcione los parámetros requeridos visitorCode y goalId.
La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval). Si prefiere enviar la solicitud de inmediato, utilice el método FlushVisitorInstantly().
Envío de eventos a soluciones de analítica
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the GetEngineTrackingCode() method.
El método GetEngineTrackingCode() recupera el código de seguimiento único necesario para enviar eventos de exposición a su solución de analítica. El uso de este método le permite registrar eventos y enviarlos a la plataforma de analítica que desee.
Experimentación entre dispositivos
Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.
Sincronización de datos personalizados entre dispositivos
Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado:
Mismo ID de usuario en todos los dispositivos
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.
Instancias multi-servidor con IDs consistentes
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() 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.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
// 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)
// 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.
Uso de datos personalizados para la fusión de sesiones
La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utilice CustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada.
After cross-device reconciliation is enabled, calling GetRemoteVisitorData() with the parameter userId retrieves all known data for a given user.
Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.
La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí.
Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon.
Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
GetRemoteVisitorData() with added UniqueIdentifier(true) - to retrieve data for all linked visitors.
TrackConversion() or Flush*() with added UniqueIdentifier(true) data - to track some data for specific visitor that is associated with another visitor.
A continuación se muestra un ejemplo de cómo usar datos personalizados para la fusión de sesiones.
// 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)
En este ejemplo, la aplicación tiene una página de inicio de sesión. Como el ID de usuario es desconocido en el momento del inicio de sesión, se utiliza un identificador de visitante anónimo generado por el método GetVisitorCode(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.
Uso de una clave de bucketing personalizada
De forma predeterminada, Kameleoon utiliza un ID de visitante anónimo y único (visitorCode) para asignar usuarios a las variaciones de los feature flags. Este ID se genera y almacena habitualmente en el dispositivo del usuario (en una cookie del navegador para los SDKs del lado del cliente y del lado del servidor, y en almacenamiento persistente para los SDKs móviles). Sin embargo, en determinados escenarios puede necesitar asegurarse de que todos los usuarios de la misma organización vean la misma variante de un feature flag.
La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitorCode predeterminado.
Casos de uso
El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:
- Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como
accountId. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y en una mejor experiencia de usuario.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:
client.AddData(visitorCode, types.NewCustomData(index, "newVisitorCode"))
- Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the
AddData() method. In this method, you will pass your chosen custom bucketing key as a CustomData object. Here, newVisitorCode refers to the identifier you wish to use for your bucketing (for example, the new userId or accountId).
Para que la clave de bucketing personalizada funcione correctamente, también debe definirse y configurarse para el feature flag durante el proceso de creación o edición del flag. Sin esta configuración correspondiente, el bucketing del SDK no aplicará su clave personalizada. Para obtener instrucciones detalladas sobre cómo configurar esto en Kameleoon, consulte este artículo.
- 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.
- Seguimiento de datos y analítica: Es crucial tener en cuenta que, aunque el
newVisitorCode (su clave personalizada) se utiliza para las decisiones de bucketing, todos los datos posteriores (eventos de seguimiento y conversiones, por ejemplo) se envían y se asocian con el visitorCode original. Esta separación garantiza que su analítica refleje con precisión los recorridos e interacciones individuales de los usuarios dentro del contexto más amplio de su experimento, incluso cuando el bucketing se realiza a un nivel superior (como una cuenta) o a través de varios dispositivos/sesiones. Sus datos originales del visitante permanecen intactos para una elaboración de informes completa.
Requisitos técnicos
Para utilizar eficazmente una clave de bucketing personalizada:
- The key must be a
string.
- Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un
userId, el ID de cada usuario debe ser único).
- La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios.
También puede utilizar sus propios datos externos para segmentar a los usuarios.
Registro de eventos
El SDK genera registros que reflejan diversos procesos internos y problemas.
Niveles de registro
El SDK admite la configuración para limitar el registro mediante un nivel de log.
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)
Gestión personalizada de los registros
El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.
El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
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())
Referencia
This is a full reference documentation of the Go SDK.
Inicialización
Create()
Llame a este método antes que a cualquier otro para inicializar el SDK. Este método se encuentra en KameleoonClientFactory. Esto crea una instancia de KameleoonClient para gestionar todas las interacciones entre el SDK y su aplicación.
const siteCode = "sitecode"
config := &kameleoon.KameleoonClientConfig{
// ...
}
client, err := KameleoonClientFactory.Create(siteCode, config)
Argumentos
| Name | Type | Description |
|---|
| siteCode (obligatorio) | string | Es la clave única del proyecto de Kameleoon que está utilizando con el SDK. |
| cfg (obligatorio) | *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. |
Valor de retorno
| 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()
Llame a este método antes que a cualquier otro para inicializar el SDK. Este método se encuentra en KameleoonClientFactory. Esto crea una instancia de KameleoonClient para gestionar todas las interacciones entre el SDK y su aplicación.
const siteCode = "sitecode"
client, err := KameleoonClientFactory.CreateFromFile(siteCode, "/etc/kameleoon/client-go.yaml")
Argumentos
| Name | Type | Description |
|---|
| siteCode (obligatorio) | string | A Kameleoon siteCode. |
| cfgPath (obligatorio) | 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. |
Valor de retorno
| 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()
El método Forget elimina una instancia de KameleoonClient del KameleoonClientFactory con el siteCode especificado y libera los recursos utilizados por la instancia de KameleoonClient. La instancia de KameleoonClient no debe utilizarse después de llamar al método Forget.
const siteCode = "sitecode"
KameleoonClientFactory.Forget(siteCode)
Argumentos
| Name | Type | Description |
|---|
| siteCode | string | The siteCode of the KameleoonClient instance to be removed from the KameleoonClientFactory. Este campo es obligatorio. |
WaitInit()
La inicialización del cliente Kameleoon no es inmediata, ya que requiere una solicitud al servidor de nuestra CDN (Content Delivery Network) para recuperar la configuración actual de todos los experimentos activos y feature flags.
El método WaitInit de kameleoon.KameleoonClient le permite esperar hasta que la instancia de KameleoonClient esté lista para usarse.
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.
}
Valor de retorno
| Type | Description |
|---|
| error | An error occurred during the initialization process. |
Feature flags y variaciones
IsFeatureActive() / IsFeatureActiveWithTracking()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Use este método si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON / OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación. Si su feature flag tiene variaciones y variables, debería utilizar el método GetVariation.
It takes a visitorCode and featureKey as mandatory arguments to check if the feature flag is active for a given user.
If the user has not been associated with your feature flag before, the SDK returns a random boolean value (true if the user should have this feature or false if not). However, if the user has already been registered with this feature flag, the SDK detects the previous feature flag value.
It is important to set up proper error handling in your code to catch any potential exceptions that may occur, as shown in the code example.
Si especifica un visitorCode, el método IsFeatureActive lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as IsFeatureActive(), GetVariation() or GetVariations().Use el valor predeterminado true para el parámetro GetVariationOptParams.Track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro GetVariationOptParams.Track en false solo si llama a estos métodos antes de exponer a los visitantes.Por ejemplo, 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.
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
}
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.
Argumentos
| Name | Type | Description |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | The key of the feature you want to expose to a user. Este campo es obligatorio. |
| isUniqueIdentifier (Obsoleto) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, el valor predeterminado es 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). |
Valor de retorno
| Type | Description |
|---|
| bool | Value of the feature flag that is registered for a given visitorCode. |
Excepciones lanzadas
| Type | Description |
|---|
| errs.FeatureConfigNotFound | This error indicates that the requested feature key could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode. |
| errs.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
GetVariation()
- 📨 Envía datos de seguimiento a Kameleoon (depending on the
GetVariationOptParams.Track parameter)
Recupera la Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitorCode and featureKey as mandatory arguments. The GetVariationOptParams.Track argument is optional and defaults to true.
Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado.
Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
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
}
Argumentos
| Name | Type | Description | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| featureKey (obligatorio) | string | Clave de la funcionalidad que desea exponer a un visitante. | |
| GetVariationOptParams.Track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
Variation | An assigned Variation to a given visitor for a specific feature flag on success, otherwise an error. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
errs.VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
errs.FeatureNotFound | Excepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación). |
errs.FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
GetVariations()
- 📨 Envía datos de seguimiento a Kameleoon (depending on the
GetVariationsOptParams.Track parameter)
Recupera un map de objetos Variation asignados a un visitante dado para todos los feature flags.
Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. 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. De forma predeterminada, it is set to true. Si se establece en false, el seguimiento estará deshabilitado.
El map devuelto consta de claves de feature flags como claves y su Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag.
Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
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
}
Argumentos
| Name | Type | Description | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| GetVariationsOptParams.OnlyActive (opcional) | bool | Parámetro opcional que indica si se deben devolver las variaciones para los feature flags activos (true) o todos (false). | false |
| GetVariationsOptParams.Track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
map[string]Variation | Map that contains the assigned Variation objects of the feature flags using the keys of the corresponding features on success, otherwise an error. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
errs.VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| 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). |
Valor de retorno
| Tipo | Descripción |
|---|
map[string]Variation | Map that contains the assigned Variations of the feature flags using the keys of the corresponding features. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
SetForcedVariation()
El método permite you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.
Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set SetForcedVariationOptParams.ForceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
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.
El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are specific to an individual experiment.
- Simulated variations: Affect the overall feature flag result.
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
}
Argumentos
| Name | Type | Description | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| experimentId (obligatorio) | int | Experiment Id que será segmentado y seleccionado durante el proceso de evaluación. | |
| variationKey (obligatorio) | string | Variation Key correspondiente a una Variation que debe forzarse como valor devuelto para el experimento. If the value is "", the forced variation will be reset. | |
| SetForcedVariationOptParams.ForceTargeting (opcional) | bool | Indica si la segmentación para el experimento debe forzarse y omitirse (true) o aplicarse como en el proceso de evaluación estándar (false). | true |
Excepciones lanzadas
| Tipo | Descripción |
|---|
errs.VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
errs.FeatureExperimentNotFound | Excepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon. |
errs.FeatureVariationNotFound | Excepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
EvaluateAudiences()
- 📨 Envía datos de seguimiento a Kameleoon
Este método evalúa a los visitantes con respecto a todos los segmentos disponibles de Audiences Explorer y realiza el seguimiento de los que coinciden.
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. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
if err := client.EvaluateAudiences(visitorCode); err != nil {
// Handling the error
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
errs.VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
GetDataFile()
To evaluate all feature flags, use GetVariations(). This method is more efficient than calling DataFile and iterating through flags with GetVariation().
Devuelve la configuración actual del SDK como un objeto DataFile.
dataFile := client.GetDataFile()
Valor de retorno
| Tipo | Descripción |
|---|
DataFile | El DataFile que contiene la configuración del SDK |
Datos del visitante
GetVisitorCode()
This method was previously called ObtainVisitorCode, which was removed in SDK version 3.0.0.
To ensure user identification consistency, especially when using Kameleoon in hybrid mode, you should call the GetVisitorCode() method to obtain the Kameleoon visitorCode for the current visitor. Here’s how it works:
-
Kameleoon checks if there is a kameleoonVisitorCode cookie associated with the current Solicitud HTTP. If found, Kameleoon this code as the visitor identifier.
-
If no cookie is found, the method will either randomly generate a new identifier, or use the defaultVisitorCode argument if it is passed. Using your identifiers as visitor codes allows you to match Kameleoon visitors with your own users without additional look-ups.
-
The server-side kameleoonVisitorCode cookie is then set with the identifier value via HTTP header and the method returns the identifier value.
Para más información, consulte este artículo.
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.
The GetVisitorCode() method allows you to set simulated variations for a visitor. Cuando las cookies (de una request o document) contienen la clave kameleoonSimulationFFData, se omite el proceso de evaluación estándar. En su lugar, el método devuelve directamente una Variation basada en los datos proporcionados.Puede aplicar simulaciones de dos formas:
- Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manualmente: Establezca la cookie
kameleoonSimulationFFData manualmente.
It’s important to distinguish simulated variations from forced variations:
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
⚙️ Manual setupAsegúrese de que la cookie kameleoonSimulationFFData siga este formato:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación con varId del experimento expId para el featureKey indicado.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para el featureKey indicado.
⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as encodeURIComponent.
visitorCode, err := client.GetVisitorCode(req, resp)
visitorCode, err := client.GetVisitorCode(req, resp, "defaultVisitorCode")
Argumentos
| Name | Type | Description |
|---|
| request | *fasthttp.Request | The current fasthttp.Request object should be passed as the first parameter. Este campo es obligatorio. |
| response | *fasthttp.Response | The current fasthttp.Response object should be passed as the second parameter. Este campo es obligatorio. |
| 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. |
Valor de retorno
| 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. |
Excepciones lanzadas
| 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()
El método AddData() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.
The AddData() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the Flush*() method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the Flush*().
El método TrackConversion() también envía cualquier dato previamente asociado, al igual que Flush*(). Lo mismo aplica para los métodos GetVariation() y GetVariations() si se desencadena una regla de experimentación.
Cada visitante solo puede tener una instancia de datos asociados para la mayoría de los tipos de datos. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.
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")
)
Argumentos
| Nombre | Tipo | Descripción | Valor predeterminado |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| track (opcional) | bool | Especifica si los datos añadidos son aptos para el seguimiento. Cuando se establece en false, los datos se almacenan localmente y se utilizan solo para la evaluación de segmentación; no se envían a la Data API de Kameleoon. | true |
| allData (obligatorio) | ...types.Data | Colección de tipos de datos de Kameleoon. | |
Excepciones
| Tipo | Descripción |
|---|
errs.VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FlushAll() / FlushVisitor() / FlushVisitorInstantly()
- 📨 Envía datos de seguimiento a 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. 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.
El método FlushVisitor()/FlushVisitorInstantly() usa visitorCode como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
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)
Argumentos
| Name | Type | Description |
|---|
| visitorCode | string | Identificador único del usuario. This field is mandatory for FlushVisitor()/FlushVisitorInstantly(). |
| isUniqueIdentifier (Obsoleto) | bool | A parameter of the FlushVisitor method for specifying if the visitorCode is a unique identifier. If not provided, el valor predeterminado es false. The field is optional. |
Excepciones lanzadas
| 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()
El método GetRemoteData() recupera datos externos almacenados en el servidor remoto de Kameleoon para el siteCode especificado (especificado en el constructor de KameleoonClient) según una key pasada como argumento. Esta clave es habitualmente el Visitor Code de Kameleoon o su User ID.
Puede utilizar este método para recuperar preferencias de usuario, datos históricos o cualquier otro dato relevante para la lógica de su aplicación. Al almacenar estos datos en nuestros servidores altamente escalables usando nuestra Data API, puede gestionar eficientemente cantidades masivas de datos y recuperarlos para todos sus visitantes o usuarios.
El valor devuelto por el método es un objeto JSON que puede decodificarse usando la función json.Unmarshal(). Puede usar estos datos para crear segmentos de segmentación avanzados para feature flags y experimentos, o para filtrar los informes de experimentos y personalización basándose en cualquier valor almacenado en los datos recuperados.
type Test1 struct {
Value string `json:"some field to insert or update"`
}
remoteData, err := s.client.GetRemoteData("USER_ID") // uses default timeout
var test1 Test1
err = json.Unmarshal(remoteData, &test1)
remoteData, err := s.client.GetRemoteData("USER_ID", 1000)
Note that, since a server call is required, this mechanism is asynchronous.
We offer built-in integrations with Mixpanel, Segment, and GA4 to fetch external cohorts and utilize them in feature experiments. The key utilized in these integrations is either our Visitor code or your User ID. You can refer to the sample code provided below to retrieve and utilize Mixpanel cohorts:
//Retrieve and use Mixpanel Cohorts
type Cohort struct {
Id string `json:"mixpanel_cohort_id"`
Name string `json:"mixpanel_cohort_name"`
ProjectId string `json:"mixpanel_cohort_project_id"`
}
type MixPanelCohorts struct {
Cohorts []Cohort `json:"mixpanel_cohorts"`
}
remoteData, err := s.client.GetRemoteData("USER_ID")
var mixPanel MixPanelCohorts
if err = json.Unmarshal(remoteData, &mixPanel); err == nil {
cohorts := make([]string, len(mixPanel.Cohorts))
for _, cohort := range mixPanel.Cohorts {
cohorts = append(cohorts, cohort.Id)
}
client.AddData(visitorCode, types.NewCustomData(customDataIndex, cohorts...))
}
Argumentos
| Name | Type | Description |
|---|
| key | string | The key with which the data you are trying to retrieve is associated. Este campo es obligatorio. 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. |
Valor de retorno
| 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. |
Excepciones lanzadas
| 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. El método añade los datos al almacenamiento para que otros métodos los utilicen al tomar decisiones de segmentación.
Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:
- use data collected from other devices.
- access a user’s history, such as previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.
De forma predeterminada, 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.
The parameter IsUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
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
)
Argumentos of GetRemoteVisitorData
| Name | Type | Description |
|---|
| visitorCode | string | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| addData | bool | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. Este campo es obligatorio. |
| 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. |
Argumentos of GetRemoteVisitorDataWithFilter
| Name | Type | Description |
|---|
| visitorCode | string | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| addData | bool | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. Este campo es obligatorio. |
| filter | types.RemoteVisitorDataFilter | Filtro para especificar qué datos deben recuperarse de las visitas. Este campo es obligatorio. |
| 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. |
Argumentos of GetRemoteVisitorDataWithOptParams
| Name | Type | Description |
|---|
| visitorCode | string | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| addData | bool | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. Este campo es obligatorio. |
| filter | types.RemoteVisitorDataFilter | Filtro para especificar qué datos deben recuperarse de las visitas. Este campo es obligatorio. |
| params | kameleoon.RemoteVisitorDataOptParams | Optional parameters. |
Here is the list of kameleoon.RemoteVisitorDataOptParams fields:| Nombre | Tipo | Descripción |
|---|
| IsUniqueIdentifier (opcional) (Obsoleto) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, el valor predeterminado es false. |
| Timeout (opcional) | 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. |
El valor predeterminado de kameleoon.RemoteVisitorDataOptParams, que es types.RemoteVisitorDataFilter{PreviousVisitAmount: 1, CurrentVisit: true, CustomData: true}, puede obtenerse con la función types.DefaultRemoteVisitorDataFilter().
Valor de retorno
| Type | Description |
|---|
| []types.Data | A slice of data assigned to the given visitor. |
| error | An occurred error. |
Using parameters in GetRemoteVisitorData()
El método GetRemoteVisitorData() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Ya sea que esté segmentando en función de objetivos, experimentos o variaciones, el mismo enfoque se aplica a todos los tipos de datos.
Por ejemplo, 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.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método GetRemoteVisitorData() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available types.RemoteVisitorDataFilter options:| Name | Type | Description | Default |
|---|
| PreviousVisitAmount (opcional) | int | Número de visitas previas de las que recuperar datos. Number between 1 and 25 | 1 |
| CurrentVisit (opcional) | bool | If true, current visit data will be retrieved | true |
| CustomData (opcional) | bool | If true, custom data will be retrieved. | true |
| PageViews (opcional) | bool | If true, page data will be retrieved. | false |
| Geolocation (opcional) | bool | If true, geolocation data will be retrieved. | false |
| Device (opcional) | bool | If true, device data will be retrieved. | false |
| Browser (opcional) | bool | If true, browser data will be retrieved. | false |
| OperatingSystem (opcional) | bool | If true, operating system data will be retrieved. | false |
| Conversions (opcional) | bool | If true, conversion data will be retrieved. | false |
| Experiments (opcional) | bool | If true, experiment data will be retrieved. | false |
| Kcs (opcional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
| VisitorCode (opcional) | 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. | true |
| Personalization (opcional) | bool | If true, personalization data will be retrieved. This is required for the personalization condition. | false |
| cbs (opcional) | bool | If true, Contextual Bandit score data will be retrieved. | false |
GetVisitorWarehouseAudience()
Retrieves all audience data associated with the visitor in your data warehouse using the specified VisitorCode and WarehouseKey. The WarehouseKey is typically your internal user ID. The CustomDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. El método devuelve a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
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})
Argumentos of GetVisitorWarehouseAudience
| Name | Type | Description |
|---|
| VisitorCode | string | A unique visitor identification string, can’t exceed 255 characters length. |
| CustomDataIndex | int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. |
| WarehouseKey | string | A unique key to identify the warehouse data (usually, your internal user ID). Este campo es opcional. |
| 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. Este campo es opcional. |
Argumentos of GetVisitorWarehouseAudienceWithOptParams
| Name | Type | Description |
|---|
| visitorCode | string | A unique visitor identification string, can’t exceed 255 characters length. |
| customDataIndex | int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. |
| params | kameleoon.VisitorWarehouseAudienceOptParams | Optional parameters. |
Here is the list of kameleoon.VisitorWarehouseAudienceOptParams fields:| Nombre | Tipo | Descripción |
|---|
| WarehouseKey | string | A unique key to identify the warehouse data (usually, your internal user ID). Este campo es opcional. |
| 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]. Este campo es opcional. |
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.
Valor de retorno
| 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.
visitorCode, err := kameleoonClient.GetVisitorCode(req, resp)
err := kameleoonClient.SetLegalConsent(visitorCode, true, resp)
Argumentos
| Name | Type | Description |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| consent | bool | Valor booleano que representa el estado del consentimiento legal. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. Este campo es obligatorio. |
| response | *fasthttp.Response | The HTTP response where values in the cookies will be adjusted based on the legal consent status. Este campo es opcional. |
Excepciones lanzadas
| 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. |
Comportamiento al revocar el consentimiento
Cuando llama a SetLegalConsent() con consent=false, el SDK no elimina la cookie kameleoonVisitorCode. En su lugar, deja de prorrogar la fecha de expiración de la cookie, permitiendo que esta persista hasta que expire de forma natural.
Si sus requisitos de cumplimiento exigen la eliminación inmediata del archivo de cookie al revocar el consentimiento, debe eliminarlo manualmente utilizando los métodos nativos de gestión de cookies de su framework. El SDK no eliminará el archivo automáticamente.
Objetivos y analítica de terceros
TrackConversion()
- 📨 Envía datos de seguimiento a Kameleoon
Use este método para track a conversion for a specific 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.
El método TrackConversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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")
},
})
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| goalId (obligatorio) | int | ID del objetivo. | |
| TrackConversionOptParams.Revenue (opcional) | float64 | Ingreso de la conversión. | 0 |
| TrackConversionOptParams.Negative (opcional) | bool | Define si el ingreso es positivo o negativo. | false |
| TrackConversionOptParams.Metadata (opcional) | []*CustomData | Le permite establecer valores específicos para los datos personalizados que se hayan definido como metadatos del objetivo en la aplicación de Kameleoon. Example: [CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]. In this example, 5 and 9 are the indexes of the custom data (5 = “Payment Type”, 9 = “Delivery Method”). | nil |
| isUniqueIdentifier (deprecated) | bool | Parámetro opcional para indicar si el visitorCode es un identificador único. | false |
TrackConversionOptParams.Metadata values are accessible through raw data exports and the results page.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() method. If the parameter is omitted, Kameleoon will use the last tracked values for those 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.En el siguiente ejemplo, 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’).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"),
},
})
Excepciones
| Tipo | Descripción |
|---|
errs.VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. 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.
Consulte experimentación híbrida para más información sobre cómo implementar este método.
engineTrackingCode := kameleoonClient.GetEngineTrackingCode(visitorCode)
- To use this feature, implement both the Go SDK and Kameleoon Engine.js. 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. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call
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 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>
En este ejemplo, 123456 y 234567 son IDs de experimento, y 7890 y 8901 son IDs de variación. En su implementación, el SDK genera estos valores en el código de seguimiento devuelto.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. |
Valor de retorno
| Tipo | Descripción |
|---|
string | Código JavaScript para insertar en la página. |
Events
OnUpdateConfiguration()
kameleoonClient.OnUpdateConfiguration(
// configuration was updated
)
El método OnUpdateConfiguration le permite gestionar el evento cuando la configuración tiene datos actualizados. Toma un parámetro de entrada, handler. El manejador que se llamará cuando la configuración se actualice mediante un evento de configuración en tiempo real.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| handler | func() | The handler that will be called when the configuration is updated using a real-time configuration event. |
Tipos de datos
Browser
El conjunto de datos Browser almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.
| Nombre | Tipo | Descripción |
|---|
| browserType (obligatorio) | BrowserType | List of browsers: BrowserTypeChrome, BrowserTypeIE, BrowserTypeFirefox, BrowserTypeSafari, BrowserTypeOpera, BrowserTypeOther. |
| version (opcional) | float32 | Version of the browser, floating point number represents major and minor version of the browser |
client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeChrome))
client.AddData(visitorCode, types.NewBrowser(types.BrowserTypeSafari, 16.0))
Conversion
El conjunto de datos Conversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
- Each visitor can have multiple
Conversion objects.
- You can find the
goalId in the Kameleoon app.
| Nombre | Tipo | Descripción | Default |
|---|
| goalId (obligatorio) | int | ID del objetivo. | |
| ConversionOptParams.Revenue (opcional) | float64 | Revenue of the conversion | 0 |
| ConversionOptParams.Negative (opcional) | bool | Define si el ingreso es positivo o negativo. | false |
| ConversionOptParams.Metadata (opcional) | []*types.CustomData | Metadatos de la conversión. | nil |
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"),
},
}),
)
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.
| Nombre | Tipo | Descripción |
|---|
| cookies | map[string]string | Map de objetos string que consta de claves y valores de cookies. Este campo es obligatorio. |
Each visitor can only have one Cookie. Adding second Cookie overwrites the first one.
cookie := types.NewCookie(map[string]string{
"k1": "v1",
"k2": "v2",
})
client.AddData(visitorCode, cookie)
Geolocation
Geolocation contains the visitor’s geolocation details.
| Nombre | Tipo | Descripción |
|---|
| country (obligatorio) | string | The country of the visitor. |
| region (opcional) | string | The region of the visitor. |
| city (opcional) | string | The city of the visitor. |
| postalCode (opcional) | string | The postal code of the visitor. |
| latitude (opcional) | float64 | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
| longitude (opcional) | float64 | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
- Each visitor can have only one
Geolocation. Adding a second Geolocation overwrites the first one.
client.AddData(visitorCode, types.NewGeolocation("France", "Île-de-France", "Paris"))
client.AddData(visitorCode, types.NewGeolocationWithCoords(48.856667, 2.352222, "France", "Île-de-France", "Paris"))
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 or as a filter/breakdown in experiment reports. To learn more about custom data, please refer to this article.
| Nombre | Tipo | Descripción | Default |
|---|
| index/name (obligatorio) | int/string | Índice o nombre del dato personalizado. Either index or name must be provided to identify the data. | |
| values (obligatorio) | ...string | The values of the custom data to be stored. | |
| overwrite (opcional) | bool | Flag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. See more | true |
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"),
)
-
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 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.
Device
Puede utilizar los datos del dispositivo para filtrar los informes de experimentos o personalización por cualquier valor asociado.
NewDevice
| Name | Type | Description |
|---|
| deviceType | DeviceType | List of devices: Phone, Tablet, Desktop. Este campo es obligatorio. |
client.AddData(visitorCode, types.NewDevice(types.DeviceTypeDesktop))
OperatingSystem
OperatingSystem contains information about the operating system on the visitor’s device.
NewOperatingSystem
| Nombre | Tipo | Descripción |
|---|
| type | types.OperatingSystemType | List of operating systems: Windows, Mac, iOS, Linux, Android and WindowsPhone. Este campo es obligatorio. |
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.
client.AddData(visitorCode, types.NewOperatingSystem(types.OperatingSystemTypeWindows))
PageView
Puede utilizar los datos de pageview para filtrar los informes de experimentos o personalización por cualquier valor asociado.
The index or ID of the referrer can be found in your Kameleoon account. It is important to note that this index starts at 0. This menas the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.
NewPageView
| Name | Type | Description |
|---|
| url | string | The URL of the page viewed. Este campo es obligatorio. |
| referrers | …int | The referrers of the viewed pages. Este campo es opcional. |
NewPageViewWithTitle
| Name | Type | Description |
|---|
| url | string | The URL of the page viewed. Este campo es obligatorio. |
| title | string | The title of the page viewed. Este campo es obligatorio. |
| referrers | …int | The referrers of the viewed pages. Este campo es opcional. |
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. Para más detalles, consulte our help article on bot filtering.
Si utiliza bots internos, le sugerimos pasar el valor curl/8.0 del userAgent para excluirlos de nuestra analítica.
NewUserAgent
| Name | Type | Description |
|---|
| value | string | The User-Agent value that will be sent with tracking requests. Este campo es obligatorio. |
client.AddData(visitorCode, types.NewUserAgent("visitor_user_agent"))
UniqueIdentifier
Si no añade UniqueIdentifier para un visitante, se utiliza visitorCode como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando añade UniqueIdentifier para un visitante, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
NewUniqueIdentifier
| Name | Type | Description |
|---|
| value | bool | Parameter for specifying if the visitor_code is a unique identifier. Este campo es obligatorio. |
client.AddData(visitorCode, types.NewUniqueIdentifier(true))
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.
NewApplicationVersion
| Nombre | Tipo | Descripción |
|---|
| version (opcional) | string | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch. |
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
El DataFile contiene los detalles de configuración del SDK.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| FeatureFlags | map[string]FeatureFlag | A map of FeatureFlag objects, keyed by feature flag keys. |
| DateModified | int64 | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
// 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
FeatureFlag representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus Variations, Rules, estado del entorno y otros detalles relacionados.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| IsEnvironmentEnabled | bool | Indica si el feature flag está habilitado en el entorno actual. |
| 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 |
// 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
Rule representa un conjunto de propiedades que definen una regla en sí — por ejemplo, sus Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| Variations | map[string]Variation | A map of Variation objects, keyed by variation keys. |
// 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).
| Nombre | Tipo | Descripción |
|---|
| 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. |
- The
Variation object provides details about the assigned variation and its associated experiment, while the 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.
// 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.
| Nombre | Tipo | Descripción |
|---|
| 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. |
// 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
These methods are deprecated and will be removed in SDK version 4.0.0.
GetFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
Este método recupera the configuration of a feature experiment with several feature variations. You can use it to get a variation key for a given user by providing the visitorCode and featureKey as mandatory arguments.
If the user has never been associated with the feature flag, the SDK returns a variation key randomly, following the feature flag rules. If the user is already registered with the feature flag, the SDK detects the previous variation key value. If the user doesn’t match any of the rules, the default value defined in Kameleoon’s feature flag delivery rules will be returned. It’s important to note that the default value may not be a variation key, but a boolean value or another data type, depending on the feature flag configuration.
Don’t forget to handle potential exceptions with proper error handling in your code. See the example code for guidance.
Si especifica un visitorCode, el método GetFeatureVariationKey lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
// 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.
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | The key of the feature you want to expose to a user. Este campo es obligatorio. |
| isUniqueIdentifier (Obsoleto) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, el valor predeterminado es false. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|
| string | Variation key of the feature flag that is registered for a given visitorCode. |
Excepciones lanzadas
| Type | Description |
|---|
| errs.FeatureConfigNotFound | This error indicates that the requested feature key could not be found in the internal configuration of the SDK. This typically occurs when the feature flag has not yet been retrieved by the SDK, which can happen if the SDK is in polling mode. |
| errs.VisitorCodeInvalid | This error is returned when the visitor code provided is invalid, meaning that it is either empty or its length exceeds 255 characters. |
| errs.FeatureEnvironmentDisabled | This error indicates that the feature flag is disabled for the current environment. |
GetActiveFeatureListForVisitor()
El método GetActiveFeatureListForVisitor() toma un parámetro visitorCode. Cuando llama a este método con un visitorCode específico, el método devuelve una lista de claves de feature flags disponibles para ese visitorCode.
Don’t forget to handle potential exceptions with proper error handling in your code. Por ejemplo, see the following code:
arrayFeatureFlagKeys, err := client.GetActiveFeatureListForVisitor(visitorCode)
Argumentos
| Name | Type | Description |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
Valor de retorno
| Type | Description |
|---|
| []string | List of feature flag keys that are active for a specific visitorCode. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| 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()
El método GetActiveFeatures() recupera información sobre los feature flags activos disponibles para el visitor code especificado.
Don’t forget to handle potential exceptions with proper error handling in your code. Por ejemplo, see the following code:
activeFeatures, err := client.GetActiveFeatures(visitorCode)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
Valor de retorno
| Tipo | Descripción |
|---|
| map[string]types.Variation | Map that contains the assigned variations of the active features using the active feature IDs as keys. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| 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()
- 📨 Envía datos de seguimiento a Kameleoon
To get a feature variable of a variation key associated with a user, call the GetFeatureVariable() method of our SDK.
Este método toma un 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.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
visitorCode, err := client.GetVisitorCode(req, resp)
featureKey := "featureKey"
variableKey = "variableKey"
if variableValue, err := s.client.GetFeatureVariable(visitorCode, featureKey, variableKey); err == nil {
// your custom code depending of variableValue
} else {
// An error occurred; the feature flag has not been found in the current configuration fetched by the SDK.
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | The key of the feature you want to expose to a user. Este campo es obligatorio. |
| variableKey | string | The name of the variable for which you want to get a value. Este campo es obligatorio. |
| isUniqueIdentifier (Obsoleto) | bool | A parameter for specifying if the visitorCode is a unique identifier. If not provided, el valor predeterminado es false. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|
| 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 |
Excepciones lanzadas
| 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 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 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()
To retrieve all variables associated with a feature flag, you must call the GetFeatureVariationVariables method. This method requires two mandatory arguments: featureKey and variationKey. El método devuelve the data with the object type, as defined in the Kameleoon Platform.
Don’t forget to handle potential exceptions with proper error handling in your code. Check out the example code for guidance.
featureKey := "test_feature_variables"
variationKey := "on"
if allVariables, err := s.client.GetFeatureVariationVariables(featureKey, variationKey); err == nil {
// your custom code
} else {
// An error occurred; the feature flag or variation doesn't exist in the client configuration
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| featureKey | string | The key of the feature flag you want to obtain. Este campo es obligatorio. |
| variationKey | string | The key of the variation you want to obtain. Este campo es obligatorio. |
Valor de retorno
| Tipo | Descripción |
|---|
| 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). |
Excepciones lanzadas
| 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 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 mode. |
| errs.FeatureEnvironmentDisabled | This error indicates that the feature flag is disabled for the current environment. |
GetFeatureList()
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.
arrayFeatureKeys := client.GetFeatureList()
Valor de retorno
| Tipo | Descripción |
|---|
[]string | List of feature flag keys |