Skip to main content
Version: Config V2

Go SDK Reference

Star on GitHub Build Status Go Report Card GoDoc Sonar Coverage Sonar Quality Gate

ConfigCat Go SDK on GitHub

Getting Started

1. Get the SDK with go

go get github.com/configcat/go-sdk/v9

2. Import the ConfigCat package

import "github.com/configcat/go-sdk/v9"

3. Create the ConfigCat client with your SDK Key

client := configcat.NewClient("#YOUR-SDK-KEY#")

4. Get your setting value

isMyAwesomeFeatureEnabled := client.GetBoolValue("isMyAwesomeFeatureEnabled", false, nil)
if isMyAwesomeFeatureEnabled {
doTheNewThing()
} else {
doTheOldThing()
}

5. Stop ConfigCat client

You can safely shut down the client instance and release all associated resources on application exit.

client.Close()

Creating the ConfigCat Client

ConfigCat Client is responsible for:

  • managing the communication between your application and ConfigCat servers.
  • caching your setting values and feature flags.
  • serving values quickly in a failsafe way.

configcat.NewClient(<sdkKey>) returns a client with default options.

ArgumentsDescription
sdkKeySDK Key to access your feature flags and configurations. Get it from ConfigCat Dashboard.

Custom client options

configcat.NewCustomClient(options) returns a customized client. The options parameter is a structure which contains the optional properties.

Available optional properties:

PropertiesTypeDescription
SDKKeystringSDK Key to access your feature flags and configurations. Get it from ConfigCat Dashboard.
DataGovernanceconfigcat.DataGovernanceDefaults to Global. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: Global, EuOnly.
BaseUrlstringObsolete Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations.
Cache ConfigCacheSets a custom cache implementation for the client. See below.
NoWaitForRefreshboolDefaults to false. When it's true the typed get methods (Get[TYPE]Value()) will never wait for a configuration refresh to complete before returning. When it's false and PollingMode is AutoPoll, the first request may block, when PollingMode is Lazy, any request may block.
HttpTimeouttime.DurationSets the maximum wait time for a HTTP response. More about the HTTP timeout
Transporthttp.RoundTripperSets the transport options for the underlying HTTP calls.
Loggerconfigcat.LoggerSets the Logger implementation used by the SDK for logging. More about logging
LogLevelconfigcat.LogLevelSets the logging verbosity. More about logging
PollingModeconfigcat.PollingModeDefaults to AutoPoll. Sets the polling mode for the client. More about polling modes.
PollIntervaltime.DurationSets after how much time a configuration is considered stale. When PollingMode is AutoPoll this value is used as the polling rate.
FlagOverrides*configcat.FlagOverridesSets the local feature flag & setting overrides. More about feature flag overrides.
DefaultUserconfigcat.UserSets the default user. More about default user.
OfflineboolDefaults to false. Indicates whether the SDK should be initialized in offline mode. More about offline mode.
Hooks*configcat.HooksUsed to subscribe events that the SDK sends in specific scenarios. More about hooks.

Then you can pass it to the NewCustomClient() method:

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
PollingMode: configcat.Manual,
Logger: configcat.DefaultLogger(configcat.LogLevelInfo)})
caution

We strongly recommend you to use the ConfigCat Client as a Singleton object in your application. If you want to use multiple SDK Keys in the same application, create only one ConfigCat Client per SDK Key.

Anatomy of Get[TYPE]Value()

Basically all of the value evaluator methods share the same signature, they only differ in their served value type. GetBoolValue() is for evaluating feature flags, GetIntValue() and GetFloatValue() are for numeric and GetStringValue() is for textual settings.

ParametersDescription
keySetting-specific key. Set on ConfigCat Dashboard for each setting.
defaultValueThis value will be returned in case of an error.
userUser Object. Essential when using Targeting. Read more about Targeting.
boolValue := client.GetBoolValue(
"keyOfMyBoolSetting", // Setting Key
false, // Default value
&configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#"} // User Object
)
intValue := client.GetIntValue(
"keyOfMyIntSetting", // Setting Key
0, // Default value
&configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#"} // User Object
)

Anatomy of Get[TYPE]ValueDetails()

GetValueDetails() is similar to GetValue() but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.

ParametersDescription
keySetting-specific key. Set on ConfigCat Dashboard for each setting.
defaultValueThis value will be returned in case of an error.
userUser Object. Essential when using Targeting. Read more about Targeting.
details := client.GetBoolValueDetails(
"keyOfMyBoolSetting", // Setting Key
false, // Default value
&configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#"} // User Object
)
details := client.GetIntValueDetails(
"keyOfMyIntSetting", // Setting Key
0, // Default value
&configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#"} // User Object
)

The details result contains the following information:

FieldTypeDescription
Valuebool / string / int / float64The evaluated value of the feature flag or setting.
Data.KeystringThe key of the evaluated feature flag or setting.
Data.IsDefaultValueboolTrue when the default value passed to Get[TYPE]ValueDetails() is returned due to an error.
Data.ErrorerrorIn case of an error, this field contains the error message.
Data.UserUserThe User Object that was used for evaluation.
Data.MatchedPercentageOption*PercentageOptionThe Percentage Option (if any) that was used to select the evaluated value.
Data.MatchedTargetingRule*TargetingRuleThe Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value.
Data.FetchTimetime.TimeThe last download time (UTC) of the current config.

User Object

The User Object is essential if you'd like to use ConfigCat's Targeting feature.

user = &configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#"}
user = &configcat.UserData{Identifier: "[email protected]"}

Customized User Object creation

ArgumentsDescription
IdentifierUnique identifier of a user in your application. Can be any value, even an email address.
EmailOptional parameter for easier Targeting Rule definitions.
CountryOptional parameter for easier Targeting Rule definitions.
CustomOptional dictionary for custom attributes of a user for advanced Targeting Rule definitions. e.g. User role, Subscription type.
custom := map[string]interface{}
custom["SubscriptionType"] = "Pro"
custom["UserRole"] = "Admin"
user := &configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#",
Email: "[email protected]",
Company: "United Kingdom",
Custom: custom}

The Custom dictionary also allows attribute values other than string values:

registeredAt, _ := time.Parse(time.DateTime, "2023-11-22 12:34:56")
custom := map[string]interface{}
custom["Rating"] = 4.5
custom["RegisteredAt"] = registeredAt
custom["Roles"] = []string{"Role1","Role2"}
user := &configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#", Custom: custom}

User Object Attribute Types

All comparators support string values as User Object attribute (in some cases they need to be provided in a specific format though, see below), but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply:

Text-based comparators (EQUALS, IS_ONE_OF, etc.)

  • accept string or []byte values,
  • all other values are automatically converted to string (a warning will be logged but evaluation will continue as normal).

SemVer-based comparators (IS_ONE_OF_SEMVER, LESS_THAN_SEMVER, GREATER_THAN_SEMVER, etc.)

  • accept string or []byte values containing a properly formatted, valid semver value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Number-based comparators (EQUALS_NUMBER, LESS_THAN_NUMBER, GREATER_THAN_OR_EQUAL_NUMBER, etc.)

  • accept float64 values and all other numeric values which can safely be converted to float64,
  • accept string or []byte values containing a properly formatted, valid float64 value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Date time-based comparators (BEFORE_DATETIME / AFTER_DATETIME)

  • accept time.Time values, which are automatically converted to a second-based Unix timestamp (time.Time values with naive timezone are considered to be in UTC),
  • accept float64 values representing a second-based Unix timestamp and all other numeric values which can safely be converted to float64,
  • accept string or []byte values containing a properly formatted, valid float64 value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

String array-based comparators (ARRAY_CONTAINS_ANY_OF / ARRAY_NOT_CONTAINS_ANY_OF)

  • accept arrays of string ([]string),
  • accept string or []byte values containing a valid JSON string which can be deserialized to an array of string,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Other options to create a User Object

  1. Using a simple map[string]interface{}. In this case the passed map is used for looking up the user attributes.

  2. Using a custom struct. The ConfigCat SDK uses reflection to determine what attributes are available on the passed type. You can either implement the UserAttributes interface - which's GetAttribute(string) interface{} method will be used to retrieve the attributes - or use a pointer to a struct which's public fields are treated as user attributes.

If a field's type is map[string]interface{}, the map is used to look up any custom attribute not found directly in the struct. There should be at most one of these fields.

Otherwise, a field type must be a numeric type, a string, a []byte, a []string or a time.Time.

Default user

There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.

You can set the default User Object on SDK initialization:

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
DefaultUser: &configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#"}})

Whenever the Get[TYPE]Value(), Get[TYPE]ValueDetails(), GetAllValues(), or GetAllValueDetails() methods are called without an explicit user parameter, the SDK will automatically use the default user as a User Object.

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
DefaultUser: &configcat.UserData{Identifier: "[email protected]"}})

// The default user will be used at the evaluation process.
value := client.GetBoolValue("keyOfMyBoolSetting", false, nil)

When the user parameter is specified on the requesting method, it takes precedence over the default user.

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
DefaultUser: &configcat.UserData{Identifier: "[email protected]"}})

otherUser = &configcat.UserData{Identifier: "[email protected]"}

// otherUser will be used at the evaluation process.
value := client.GetBoolValue("keyOfMyBoolSetting", false, otherUser)

Polling Modes

The ConfigCat SDK supports 3 different polling mechanisms to acquire the setting values from ConfigCat. After latest setting values are downloaded, they are stored in the internal cache then all value retrievals are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.
More about polling modes.

Auto polling (default)

The ConfigCat SDK downloads the latest values and stores them automatically every 60 seconds.

Use the the PollInterval option parameter of the ConfigCat Client to change the polling interval.

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
PollingMode: configcat.AutoPoll,
PollInterval: time.Second * 120 /* polling interval in seconds */})

Lazy loading

When calling GetBoolValue(), GetIntValue(), GetFloatValue() or GetStringValue() the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case, when the NoWaitForRefresh option is false the new setting value will be returned right after the cache update. When it's set to true the setting value retrievals will not wait for the downloads and they will return immediately with the previous setting value.

Use the PollInterval option parameter of the ConfigCat Client to set the cache TTL.

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
PollingMode: configcat.Lazy,
PollInterval: time.Second * 120 /* cache TTL in seconds */})

Manual polling

Manual polling gives you full control over when the config JSON (with the setting values) is downloaded. ConfigCat SDK will not update them automatically. Calling Refresh() is your application's responsibility.

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
PollingMode: configcat.Manual})

client.Refresh()

The setting value retrieval methods will return defaultValue if the cache is empty. Call Refresh() to update the cache.

Hooks

With the following hooks you can subscribe to particular events fired by the SDK:

  • OnConfigChanged(): This event is sent when the SDK loads a new config JSON into memory from cache or via HTTP.

  • OnFlagEvaluated(EvaluationDetails): This event is sent each time when the SDK evaluates a feature flag or setting. The event sends the same evaluation details that you would get from Get[TYPE]ValueDetails().

  • OnError(error): This event is sent when an error occurs within the ConfigCat SDK.

You can subscribe to these events on SDK initialization:

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
Hooks: &configcat.Hooks{OnFlagEvaluated: func(details *EvaluationDetails) {
/* handle the event */
}})

Online / Offline mode

In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:

client.SetOffline()

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To put the SDK back in online mode, you can do the following:

client.SetOnline()

With client.IsOffline() you can check whether the SDK is in offline mode.

GetAllKeys()

You can get all the setting keys by calling the GetAllKeys() method of the ConfigCat Client.

client := configcat.NewClient("#YOUR-SDK-KEY#")
keys := client.GetAllKeys()

GetAllValues()

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

client := configcat.NewClient("#YOUR-SDK-KEY#")
settingValues := client.GetAllValues(nil)

// invoke with User Object
user := &configcat.UserData{Identifier: "#UNIQUE-USER-IDENTIFIER#"}
settingValuesTargeting := client.GetAllValues(user)

Flag Overrides

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

  • Local only (LocalOnly): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

  • Local over remote (LocalOverRemote): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

  • Remote over local (RemoteOverLocal): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can load your feature flag & setting overrides from a file or from a simple map[string]interface{} structure.

JSON File

The SDK can load your feature flag & setting overrides from a file.

client := configcat.NewCustomClient(configcat.Config{
SDKKey: "localhost",
FlagOverrides: &configcat.FlagOverrides{
FilePath: "path/to/local_flags.json",
Behavior: configcat.LocalOnly,
},
})

JSON File Structure

The SDK supports 2 types of JSON structures to describe feature flags & settings.

1. Simple (key-value) structure
{
"flags": {
"enabledFeature": true,
"disabledFeature": false,
"intSetting": 5,
"doubleSetting": 3.14,
"stringSetting": "test"
}
}

This is the same format that the SDK downloads from the ConfigCat CDN. It allows the usage of all features that are available on the ConfigCat Dashboard.

You can download your current config JSON from ConfigCat's CDN and use it as a baseline.

A convenient way to get the config JSON for a specific SDK Key is to install the ConfigCat CLI tool and execute the following command:

configcat config-json get -f v6 -p {YOUR-SDK-KEY} > config.json

(Depending on your Data Governance settings, you may need to add the --eu switch.)

Alternatively, you can download the config JSON manually, based on your Data Governance settings:

  • GLOBAL: https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json
  • EU: https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json
{
"p": {
// hash salt, required only when confidential text comparator(s) are used
"s": "80xCU/SlDz1lCiWFaxIBjyJeJecWjq46T4eu6GtozkM="
},
"s": [ // array of segments
{
"n": "Beta Users", // segment name
"r": [ // array of User Conditions (there is a logical AND relation between the elements)
{
"a": "Email", // comparison attribute
"c": 0, // comparator (see below)
"l": [ // comparison value (see below)
"[email protected]", "[email protected]"
]
}
]
}
],
"f": { // key-value map of feature flags & settings
"isFeatureEnabled": { // key of a particular flag / setting
"t": 0, // setting type, possible values:
// 0 -> on/off setting (feature flag)
// 1 -> text setting
// 2 -> whole number setting
// 3 -> decimal number setting
"r": [ // array of Targeting Rules (there is a logical OR relation between the elements)
{
"c": [ // array of conditions (there is a logical AND relation between the elements)
{
"u": { // User Condition
"a": "Email", // comparison attribute
"c": 2, // comparator, possible values and required comparison value types:
// 0 -> IS ONE OF (cleartext) + string array comparison value ("l")
// 1 -> IS NOT ONE OF (cleartext) + string array comparison value ("l")
// 2 -> CONTAINS ANY OF (cleartext) + string array comparison value ("l")
// 3 -> NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l")
// 4 -> IS ONE OF (semver) + semver string array comparison value ("l")
// 5 -> IS NOT ONE OF (semver) + semver string array comparison value ("l")
// 6 -> < (semver) + semver string comparison value ("s")
// 7 -> <= (semver + semver string comparison value ("s")
// 8 -> > (semver) + semver string comparison value ("s")
// 9 -> >= (semver + semver string comparison value ("s")
// 10 -> = (number) + number comparison value ("d")
// 11 -> <> (number + number comparison value ("d")
// 12 -> < (number) + number comparison value ("d")
// 13 -> <= (number + number comparison value ("d")
// 14 -> > (number) + number comparison value ("d")
// 15 -> >= (number) + number comparison value ("d")
// 16 -> IS ONE OF (hashed) + string array comparison value ("l")
// 17 -> IS NOT ONE OF (hashed) + string array comparison value ("l")
// 18 -> BEFORE (UTC datetime) + second-based Unix timestamp number comparison value ("d")
// 19 -> AFTER (UTC datetime) + second-based Unix timestamp number comparison value ("d")
// 20 -> EQUALS (hashed) + string comparison value ("s")
// 21 -> NOT EQUALS (hashed) + string comparison value ("s")
// 22 -> STARTS WITH ANY OF (hashed) + string array comparison value ("l")
// 23 -> NOT STARTS WITH ANY OF (hashed) + string array comparison value ("l")
// 24 -> ENDS WITH ANY OF (hashed) + string array comparison value ("l")
// 25 -> NOT ENDS WITH ANY OF (hashed) + string array comparison value ("l")
// 26 -> ARRAY CONTAINS ANY OF (hashed) + string array comparison value ("l")
// 27 -> ARRAY NOT CONTAINS ANY OF (hashed) + string array comparison value ("l")
// 28 -> EQUALS (cleartext) + string comparison value ("s")
// 29 -> NOT EQUALS (cleartext) + string comparison value ("s")
// 30 -> STARTS WITH ANY OF (cleartext) + string array comparison value ("l")
// 31 -> NOT STARTS WITH ANY OF (cleartext) + string array comparison value ("l")
// 32 -> ENDS WITH ANY OF (cleartext) + string array comparison value ("l")
// 33 -> NOT ENDS WITH ANY OF (cleartext + string array comparison value ("l")
// 34 -> ARRAY CONTAINS ANY OF (cleartext) + string array comparison value ("l")
// 35 -> ARRAY NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l")
"l": [ // comparison value - depending on the comparator, another type of value may need
// to be specified (see above):
// "s": string
// "d": number
"@example.com"
]
}
},
{
"p": { // Flag Condition (Prerequisite)
"f": "mainIntFlag", // key of prerequisite flag
"c": 0, // comparator, possible values: 0 -> EQUALS, 1 -> NOT EQUALS
"v": { // comparison value (value's type must match the prerequisite flag's type)
"i": 42
}
}
},
{
"s": { // Segment Condition
"s": 0, // segment index, a valid index into the top-level segment array ("s")
"c": 1 // comparator, possible values: 0 -> IS IN SEGMENT, 1 -> IS NOT IN SEGMENT
}
}
],
"s": { // alternatively, an array of Percentage Options ("p", see below) can also be specified
"v": { // the value served when the rule is selected during evaluation
"b": true
},
"i": "bcfb84a7"
}
}
],
"p": [ // array of Percentage Options
{
"p": 10, // % value
"v": { // the value served when the Percentage Option is selected during evaluation
"b": true
},
"i": "bcfb84a7"
},
{
"p": 90,
"v": {
"b": false
},
"i": "bddac6ae"
}
],
"v": { // fallback value, served when none of the Targeting Rules match,
// no Percentage Options are defined or evaluation of these is not possible
"b": false // depending on the setting type, another type of value may need to be specified:
// text setting -> "s": string
// whole number setting -> "i": number
// decimal number setting -> "d": number
},
"i": "430bded3" // variation id (for analytical purposes)
}
}
}

For a more comprehensive specification of the config JSON v6 format, you may refer to this JSON schema document.

Map

You can set up the SDK to load your feature flag & setting overrides from a map[string]interface{}.

client := configcat.NewCustomClient(configcat.Config{
SDKKey: "localhost",
FlagOverrides: &configcat.FlagOverrides{
Values: map[string]interface{}{
"enabledFeature": true,
"disabledFeature": false,
"intSetting": 5,
"doubleSetting": 3.14,
"stringSetting": "test",
},
Behavior: configcat.LocalOnly,
},
})

Snapshots

A Snapshot represents an immutable state of the given User's current setting values. Because of the immutability they are suitable for sharing between components that rely more on a consistent data state rather than maintaining their own states with individual get setting value calls.

Snapshot creation:

snapshot := client.Snapshot(user)

You can define setting descriptors that could be also shared between those components and used for evaluation:

boolSettingDescriptor := configcat.Bool("keyOfMyBoolSetting" /* Setting Key */, false /* Default value */)

Then you can use the descriptor to retrieve the setting's value from a snapshot:

boolValue := boolSettingDescriptor.Get(snapshot)

Custom Cache

The ConfigCat SDK stores the downloaded config data in a local cache to minimize network traffic and enhance client performance. If you prefer to use your own cache solution, such as an external or distributed cache in your system, you can implement the ConfigCache interface.

type CustomCache struct {
}

func (cache *CustomCache) Get(ctx context.Context, key string) ([]byte, error) {
// here you have to return with the cached value
}

func (cache *CustomCache) Set(ctx context.Context, key string, value []byte) error {
// here you have to store the new value in the cache
}

Then use your custom cache implementation:

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
Cache: CustomCache{}})
info

The Go SDK supports shared caching. You can read more about this feature and the required minimum SDK versions here.

Force refresh

Call the Refresh() method on the client to download the latest config JSON and update the cache.

You can also use the RefreshIfOlder() variant when you want to add expiration time windows for local cache updates.

HTTP Proxy

You can use the Transport config option to set up http transport related (like proxy) settings for the http client used by the SDK:

proxyURL, _ := url.Parse("<PROXY-URL>")
client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
})

HTTP Timeout

You can set the maximum wait time for a ConfigCat HTTP response.

client := configcat.NewCustomClient(configcat.Config{SDKKey: "#YOUR-SDK-KEY#",
HTTPTimeout: time.Second * 10
})

Logging

The default logger implementation used by the SDK is based on the log package, but you have the option to override it with your logger via the Logger config option. It only has to satisfy the Logger interface:

type Logger interface {
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}

Setting log levels

import {
"github.com/configcat/go-sdk/v9"
}

client := configcat.NewCustomClient(configcat.Config{
SDKKey: "#YOUR-SDK-KEY#",
LogLevel: configcat.LogLevelInfo})

Available log levels:

LevelDescription
LogLevelNoneTurns off logging.
LogLevelErrorOnly error level events are logged.
LogLevelWarnDefault, Errors and Warnings are logged.
LogLevelInfoErrors, Warnings and feature flag evaluation is logged.
LogLevelDebugAll of the above plus debug info is logged.

Info level logging helps to inspect the feature flag evaluation process:

[ConfigCat] 2024/01/08 13:27:56 INFO: [5000] Evaluating 'isPOCFeatureEnabled' for User '&configcat.UserData{Identifier:"##SOME-USER-IDENTIFICATION##", Email:"[email protected]", Country:"", Custom:map[string]interface{}(nil)}'
Evaluating targeting rules and applying the first match if any:
- IF User.Email CONTAINS ANY OF ['@something.com'] => false, skipping the remaining AND conditions
THEN 'false' => no match
- IF User.Email CONTAINS ANY OF ['@example.com'] => true
THEN 'true' => MATCH, applying rule
Returning 'true'.

Sample Applications

Look under the hood