configcat

package module
v9.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2024 License: MIT Imports: 23 Imported by: 8

README

ConfigCat SDK for Go

https://configcat.com

ConfigCat SDK for Go provides easy integration for your application to ConfigCat.

ConfigCat is a feature flag and configuration management service that lets you separate releases from deployments. You can turn your features ON/OFF using ConfigCat Dashboard even after they are deployed. ConfigCat lets you target specific groups of users based on region, email or any other custom user attribute.

ConfigCat is a hosted feature flag service. Manage feature toggles across frontend, backend, mobile, desktop apps. Alternative to LaunchDarkly. Management app + feature flag SDKs.

Build Status Go Report Card GoDoc Sonar Coverage Sonar Quality Gate

Getting started

1. Install the package with go
go get github.com/configcat/go-sdk/v9
2. Go to the ConfigCat Dashboard to get your SDK Key:

SDK-KEY

3. Import the ConfigCat client package to your application
import "github.com/configcat/go-sdk/v9"
4. Create a ConfigCat client instance:
client := configcat.NewClient("#YOUR-SDK-KEY#")
5. Get your setting value:
isMyAwesomeFeatureEnabled := client.GetBoolValue("isMyAwesomeFeatureEnabled", false, nil)
if isMyAwesomeFeatureEnabled {
    DoTheNewThing()
} else {
    DoTheOldThing()
}
6. Close ConfigCat client on application exit:
client.Close()

Getting user specific setting values with Targeting

Using this feature, you will be able to get different setting values for different users in your application by passing a UserData struct to the specific setting evaluation method (GetBoolValue(), GetStringValue(), GetIntValue(), GetFloatValue()).

Read more about Targeting here.

user := &configcat.UserData{Identifier: "#USER-IDENTIFIER#"}

isMyAwesomeFeatureEnabled := client.GetBoolValue("isMyAwesomeFeatureEnabled", false, user)
if isMyAwesomeFeatureEnabled {
    DoTheNewThing()
} else {
    DoTheOldThing()
}

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 requests are served from there. Read more about Polling Modes and how to use them at ConfigCat Docs.

Need help?

https://configcat.com/support

Contributing

Contributions are welcome. For more info please read the Contribution Guideline.

About ConfigCat

Documentation

Overview

Package configcat contains the Go SDK of ConfigCat (https://configcat.com)

Index

Constants

View Source
const (
	// LocalOnly means that when evaluating values, the SDK will not use feature flags and settings from the
	// ConfigCat CDN, but it will use all feature flags and settings that are loaded from local-override sources.
	LocalOnly = 0

	// LocalOverRemote means that when evaluating values, the SDK will use all feature flags and settings that are
	// downloaded from the ConfigCat CDN, plus all feature flags and settings that are loaded from
	// local-override sources. If a feature flag or a setting is defined both in the fetched and the local-override
	// source then the local-override version will take precedence.
	LocalOverRemote = 1

	// RemoteOverLocal means when evaluating values, the SDK will use all feature flags and settings that are
	// downloaded from the ConfigCat CDN, plus all feature flags and settings that are loaded from local-override
	// sources. If a feature flag or a setting is defined both in the fetched and the local-override source then the
	// fetched version will take precedence.
	RemoteOverLocal = 2
)
View Source
const DefaultPollInterval = 60 * time.Second

Variables

This section is empty.

Functions

This section is empty.

Types

type BoolEvaluationDetails

type BoolEvaluationDetails struct {
	Data  EvaluationDetailsData
	Value bool
}

BoolEvaluationDetails holds the additional evaluation information along with the value of a bool flag.

type BoolFlag

type BoolFlag struct {
	// contains filtered or unexported fields
}

func Bool

func Bool(key string, defaultValue bool) BoolFlag

Bool returns a representation of a boolean-valued flag. This can to be used as the value of a global variable for a specific flag; for example:

var fooFlag = configcat.Bool("foo", false)

func someRequest(client *configcat.Client) {
	if fooFlag.Get(client.Snapshot()) {
		// foo is enabled.
	}
}

func (BoolFlag) Get

func (f BoolFlag) Get(snap *Snapshot) bool

Get reports whether the flag is enabled with respect to the given snapshot. It returns the flag's default value if snap is nil or the key isn't in the configuration.

func (BoolFlag) GetValue

func (f BoolFlag) GetValue(snap *Snapshot) interface{}

GetValue implements Flag.GetValue.

func (BoolFlag) GetValueDetails

func (f BoolFlag) GetValueDetails(snap *Snapshot) EvaluationDetails

GetValueDetails implements Flag.GetValueDetails.

func (BoolFlag) GetWithDetails

func (f BoolFlag) GetWithDetails(snap *Snapshot) BoolEvaluationDetails

GetWithDetails returns the evaluation details along with the flag's value. It returns BoolEvaluationDetails with the flag's default value if snap is nil or the key isn't in the configuration.

func (BoolFlag) Key

func (f BoolFlag) Key() string

Key returns the name of the flag as passed to Bool.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an object for handling configurations provided by ConfigCat.

func NewClient

func NewClient(sdkKey string) *Client

NewClient returns a new Client value that access the default ConfigCat servers using the given SDK key.

The GetBoolValue, GetIntValue, GetFloatValue and GetStringValue methods can be used to find out current feature flag values. These methods will always return immediately without waiting - if there is no configuration available, they'll return a default value.

func NewCustomClient

func NewCustomClient(cfg Config) *Client

NewCustomClient initializes a new ConfigCat Client with advanced configuration.

func (*Client) Close

func (client *Client) Close()

Close shuts down the client. After closing, it shouldn't be used.

func (*Client) GetAllKeys

func (client *Client) GetAllKeys() []string

GetAllKeys returns all the known keys.

func (*Client) GetAllValueDetails

func (client *Client) GetAllValueDetails(user User) []EvaluationDetails

GetAllValueDetails returns values along with evaluation details of all feature flags and settings.

func (*Client) GetAllValues

func (client *Client) GetAllValues(user User) map[string]interface{}

GetAllValues returns all keys and values in a key-value map.

func (*Client) GetBoolValue

func (client *Client) GetBoolValue(key string, defaultValue bool, user User) bool

GetBoolValue returns the value of a boolean-typed feature flag, or defaultValue if no value can be found. If user is non-nil, it will be used to choose the value (see the User documentation for details). If user is nil and Config.DefaultUser was non-nil, that will be used instead.

In Lazy refresh mode, this can block indefinitely while the configuration is fetched. Use RefreshIfOlder explicitly if explicit control of timeouts is needed.

func (*Client) GetBoolValueDetails

func (client *Client) GetBoolValueDetails(key string, defaultValue bool, user User) BoolEvaluationDetails

GetBoolValueDetails returns the value and evaluation details of a boolean-typed feature flag. If user is non-nil, it will be used to choose the value (see the User documentation for details). If user is nil and Config.DefaultUser was non-nil, that will be used instead.

In Lazy refresh mode, this can block indefinitely while the configuration is fetched. Use RefreshIfOlder explicitly if explicit control of timeouts is needed.

func (*Client) GetFloatValue

func (client *Client) GetFloatValue(key string, defaultValue float64, user User) float64

GetFloatValue is like GetBoolValue except for float-typed (decimal number) feature flags.

func (*Client) GetFloatValueDetails

func (client *Client) GetFloatValueDetails(key string, defaultValue float64, user User) FloatEvaluationDetails

GetFloatValueDetails is like GetBoolValueDetails except for float-typed (decimal number) feature flags.

func (*Client) GetIntValue

func (client *Client) GetIntValue(key string, defaultValue int, user User) int

GetIntValue is like GetBoolValue except for int-typed (whole number) feature flags.

func (*Client) GetIntValueDetails

func (client *Client) GetIntValueDetails(key string, defaultValue int, user User) IntEvaluationDetails

GetIntValueDetails is like GetBoolValueDetails except for int-typed (whole number) feature flags.

func (*Client) GetKeyValueForVariationID

func (client *Client) GetKeyValueForVariationID(id string) (string, interface{})

GetKeyValueForVariationID returns the key and value that are associated with the given variation ID. If the variation ID isn't found, it returns "", nil.

func (*Client) GetStringValue

func (client *Client) GetStringValue(key string, defaultValue string, user User) string

GetStringValue is like GetBoolValue except for string-typed (text) feature flags.

func (*Client) GetStringValueDetails

func (client *Client) GetStringValueDetails(key string, defaultValue string, user User) StringEvaluationDetails

GetStringValueDetails is like GetBoolValueDetails except for string-typed (text) feature flags.

func (*Client) IsOffline

func (client *Client) IsOffline() bool

IsOffline returns true when the SDK is configured not to initiate HTTP requests, otherwise false.

func (*Client) Ready

func (client *Client) Ready() <-chan struct{}

Ready indicates whether the SDK is initialized with feature flag data. When the polling mode is Manual or Lazy, the SDK is considered ready right after instantiation. When the polling mode is AutoPoll, Ready closes when the first initial HTTP request is finished.

func (*Client) Refresh

func (client *Client) Refresh(ctx context.Context) error

Refresh refreshes the cached configuration. If the context is canceled while the refresh is in progress, Refresh will return but the underlying HTTP request will not be canceled.

func (*Client) RefreshIfOlder

func (client *Client) RefreshIfOlder(ctx context.Context, age time.Duration) error

RefreshIfOlder is like Refresh but refreshes the configuration only if the most recently fetched configuration is older than the given age.

func (*Client) SetOffline

func (client *Client) SetOffline()

SetOffline configures the SDK to not initiate HTTP requests.

func (*Client) SetOnline

func (client *Client) SetOnline()

SetOnline configures the SDK to allow HTTP requests.

func (*Client) Snapshot

func (client *Client) Snapshot(user User) *Snapshot

Snapshot returns an immutable snapshot of the most recent feature flags retrieved by the client, associated with the given user, or Config.DefaultUser if user is nil.

type Comparator

type Comparator uint8

Comparator is the User Object attribute comparison operator used during the evaluation process.

const (
	// OpOneOf Checks whether the comparison attribute is equal to any of the comparison values.
	OpOneOf Comparator = 0
	// OpNotOneOf Checks whether the comparison attribute is not equal to any of the comparison values.
	OpNotOneOf Comparator = 1
	// OpContains Checks whether the comparison attribute contains any comparison values as a substring.
	OpContains Comparator = 2
	// OpNotContains Checks whether the comparison attribute does not contain any comparison values as a substring.
	OpNotContains Comparator = 3
	// OpOneOfSemver Checks whether the comparison attribute interpreted as a semantic version is equal to any of the comparison values.
	OpOneOfSemver Comparator = 4
	// OpNotOneOfSemver Checks whether the comparison attribute interpreted as a semantic version is not equal to any of the comparison values.
	OpNotOneOfSemver Comparator = 5
	// OpLessSemver Checks whether the comparison attribute interpreted as a semantic version is less than the comparison value.
	OpLessSemver Comparator = 6
	// OpLessEqSemver Checks whether the comparison attribute interpreted as a semantic version is less than or equal to the comparison value.
	OpLessEqSemver Comparator = 7
	// OpGreaterSemver Checks whether the comparison attribute interpreted as a semantic version is greater than the comparison value.
	OpGreaterSemver Comparator = 8
	// OpGreaterEqSemver Checks whether the comparison attribute interpreted as a semantic version is greater than or equal to the comparison value.
	OpGreaterEqSemver Comparator = 9
	// OpEqNum Checks whether the comparison attribute interpreted as a decimal number is equal to the comparison value.
	OpEqNum Comparator = 10
	// OpNotEqNum Checks whether the comparison attribute interpreted as a decimal number is not equal to the comparison value.
	OpNotEqNum Comparator = 11
	// OpLessNum Checks whether the comparison attribute interpreted as a decimal number is less than the comparison value.
	OpLessNum Comparator = 12
	// OpLessEqNum Checks whether the comparison attribute interpreted as a decimal number is less than or equal to the comparison value.
	OpLessEqNum Comparator = 13
	// OpGreaterNum Checks whether the comparison attribute interpreted as a decimal number is greater than the comparison value.
	OpGreaterNum Comparator = 14
	// OpGreaterEqNum Checks whether the comparison attribute interpreted as a decimal number is greater than or equal to the comparison value.
	OpGreaterEqNum Comparator = 15
	// OpOneOfHashed Checks whether the comparison attribute is equal to any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpOneOfHashed Comparator = 16
	// OpNotOneOfHashed Checks whether the comparison attribute is not equal to any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpNotOneOfHashed Comparator = 17
	// OpBeforeDateTime Checks whether the comparison attribute interpreted as the seconds elapsed since Unix Epoch is less than the comparison value.
	OpBeforeDateTime Comparator = 18
	// OpAfterDateTime Checks whether the comparison attribute interpreted as the seconds elapsed since Unix Epoch is greater than the comparison value.
	OpAfterDateTime Comparator = 19
	// OpEqHashed Checks whether the comparison attribute is equal to the comparison value (where the comparison is performed using the salted SHA256 hashes of the values).
	OpEqHashed Comparator = 20
	// OpNotEqHashed Checks whether the comparison attribute is not equal to the comparison value (where the comparison is performed using the salted SHA256 hashes of the values).
	OpNotEqHashed Comparator = 21
	// OpStartsWithAnyOfHashed Checks whether the comparison attribute starts with any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpStartsWithAnyOfHashed Comparator = 22
	// OpNotStartsWithAnyOfHashed Checks whether the comparison attribute does not start with any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpNotStartsWithAnyOfHashed Comparator = 23
	// OpEndsWithAnyOfHashed Checks whether the comparison attribute ends with any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpEndsWithAnyOfHashed Comparator = 24
	// OpNotEndsWithAnyOfHashed Checks whether the comparison attribute does not end with any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpNotEndsWithAnyOfHashed Comparator = 25
	// OpArrayContainsAnyOfHashed Checks whether the comparison attribute interpreted as a string list contains any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpArrayContainsAnyOfHashed Comparator = 26
	// OpArrayNotContainsAnyOfHashed Checks whether the comparison attribute interpreted as a string list does not contain any of the comparison values (where the comparison is performed using the salted SHA256 hashes of the values).
	OpArrayNotContainsAnyOfHashed Comparator = 27
	// OpEq Checks whether the comparison attribute is equal to the comparison value.
	OpEq Comparator = 28
	// OpNotEq Checks whether the comparison attribute is not equal to the comparison value.
	OpNotEq Comparator = 29
	// OpStartsWithAnyOf Checks whether the comparison attribute starts with any of the comparison values.
	OpStartsWithAnyOf Comparator = 30
	// OpNotStartsWithAnyOf Checks whether the comparison attribute does not start with any of the comparison values.
	OpNotStartsWithAnyOf Comparator = 31
	// OpEndsWithAnyOf Checks whether the comparison attribute ends with any of the comparison values.
	OpEndsWithAnyOf Comparator = 32
	// OpNotEndsWithAnyOf Checks whether the comparison attribute does not end with any of the comparison values.
	OpNotEndsWithAnyOf Comparator = 33
	// OpArrayContainsAnyOf Checks whether the comparison attribute interpreted as a string list contains any of the comparison values.
	OpArrayContainsAnyOf Comparator = 34
	// OpArrayNotContainsAnyOf Checks whether the comparison attribute interpreted as a string list does not contain any of the comparison values.
	OpArrayNotContainsAnyOf Comparator = 35
)

func (Comparator) IsDateTime

func (op Comparator) IsDateTime() bool

func (Comparator) IsList

func (op Comparator) IsList() bool

func (Comparator) IsNumeric

func (op Comparator) IsNumeric() bool

func (Comparator) IsSensitive

func (op Comparator) IsSensitive() bool

func (Comparator) String

func (op Comparator) String() string

type Condition

type Condition struct {
	// UserCondition describes a condition that works with User Object attributes.
	UserCondition *UserCondition `json:"u"`
	// UserCondition describes a condition that works with a segment.
	SegmentCondition *SegmentCondition `json:"s"`
	// UserCondition describes a condition that works with a prerequisite flag.
	PrerequisiteFlagCondition *PrerequisiteFlagCondition `json:"p"`
}

Condition is the discriminated union of UserCondition, SegmentCondition, and PrerequisiteFlagCondition.

type Config

type Config struct {
	// SDKKey holds the key for the SDK. This parameter
	// is mandatory.
	SDKKey string

	// Logger is used to log information about configuration evaluation
	// and issues. If it's nil, DefaultLogger() will be used.
	// It assumes that the logging level will not be increased
	// during the lifetime of the client.
	Logger Logger

	// LogLevel determines the logging verbosity.
	LogLevel LogLevel

	// Cache is used to cache configuration values.
	// If it's nil, no caching will be done.
	Cache ConfigCache

	// BaseURL holds the URL of the ConfigCat CDN server.
	// If this is empty, an appropriate URL will be chosen
	// based on the DataGovernance parameter.
	BaseURL string

	// Transport is used as the HTTP transport for
	// requests to the CDN. If it's nil, http.DefaultTransport
	// will be used.
	Transport http.RoundTripper

	// HTTPTimeout holds the timeout for HTTP requests
	// made by the client. If it's zero, DefaultHTTPTimeout
	// will be used. If it's negative, no timeout will be
	// used.
	HTTPTimeout time.Duration

	// PollingMode specifies how the configuration is refreshed.
	// The zero value (default) is AutoPoll.
	PollingMode PollingMode

	// NoWaitForRefresh specifies that a Client get method (GetBoolValue,
	// GetIntValue, GetFloatValue, GetStringValue) should never wait for a
	// configuration refresh to complete before returning.
	//
	// By default, when this is false, if PollingMode is AutoPoll,
	// the first request may block, and if PollingMode is Lazy, any
	// request may block.
	NoWaitForRefresh bool

	// PollInterval specifies how old a configuration can
	// be before it's considered stale. If this is less
	// than 1, DefaultPollInterval is used.
	//
	// This parameter is ignored when PollingMode is Manual.
	PollInterval time.Duration

	// DataGovernance specifies the data governance mode.
	// Set this parameter to be in sync with the Data Governance
	// preference on the Dashboard at
	// https://app.configcat.com/organization/data-governance
	// (only Organization Admins have access).
	// The default is Global.
	DataGovernance DataGovernance

	// DefaultUser holds the default user information to associate
	// with the Flagger, used whenever a nil User is passed.
	// This usually won't contain user-specific
	// information, but it may be useful when feature flags are dependent
	// on attributes of the current machine or similar. It's somewhat
	// more efficient to use DefaultUser=u than to call flagger.Snapshot(u)
	// on every feature flag evaluation.
	DefaultUser User

	// FlagOverrides holds the feature flag and setting overrides.
	FlagOverrides *FlagOverrides

	// Hooks controls the events sent by Client.
	Hooks *Hooks

	// Offline indicates whether the SDK should be initialized in offline mode or not.
	Offline bool
}

Config describes configuration options for the Client.

type ConfigCache

type ConfigCache interface {
	// Get reads the configuration from the cache.
	Get(ctx context.Context, key string) ([]byte, error)
	// Set writes the configuration into the cache.
	Set(ctx context.Context, key string, value []byte) error
}

ConfigCache is a cache API used to make custom cache implementations.

type ConfigJson

type ConfigJson struct {
	// Settings is the map of the available feature flags and settings.
	Settings map[string]*Setting `json:"f"`
	// Segments is the list of available segments.
	Segments []*Segment `json:"s"`
	// Preferences contains additional metadata.
	Preferences *Preferences `json:"p"`
}

ConfigJson describes a ConfigCat config JSON.

type DataGovernance

type DataGovernance int

DataGovernance describes the location of your feature flag and setting data within the ConfigCat CDN.

const (
	// Global Select this if your feature flags are published to all global CDN nodes.
	Global DataGovernance = 0
	// EUOnly Select this if your feature flags are published to CDN nodes only in the EU.
	EUOnly DataGovernance = 1
)

type ErrConfigJsonMissing added in v9.0.4

type ErrConfigJsonMissing struct {
	Key string
}

ErrConfigJsonMissing is returned when the config JSON is empty or missing.

func (ErrConfigJsonMissing) Error added in v9.0.4

func (e ErrConfigJsonMissing) Error() string

type ErrKeyNotFound

type ErrKeyNotFound struct {
	Key           string
	AvailableKeys []string
}

ErrKeyNotFound is returned when a key is not found in the configuration.

func (ErrKeyNotFound) Error

func (e ErrKeyNotFound) Error() string

type ErrSettingTypeMismatch added in v9.0.4

type ErrSettingTypeMismatch struct {
	Key          string
	Value        interface{}
	ExpectedType string
}

ErrSettingTypeMismatch is returned when a requested setting type doesn't match with the expected type.

func (ErrSettingTypeMismatch) Error added in v9.0.4

func (e ErrSettingTypeMismatch) Error() string

type EvaluationDetails

type EvaluationDetails struct {
	Data  EvaluationDetailsData
	Value interface{}
}

EvaluationDetails holds the additional evaluation information along with the value of a feature flag or setting.

type EvaluationDetailsData

type EvaluationDetailsData struct {
	Key                     string
	VariationID             string
	User                    User
	IsDefaultValue          bool
	Error                   error
	FetchTime               time.Time
	MatchedTargetingRule    *TargetingRule
	MatchedPercentageOption *PercentageOption
}

EvaluationDetailsData holds the additional evaluation information of a feature flag or setting.

type Flag

type Flag interface {
	// Key returns the flag's key.
	Key() string

	// GetValue returns the flag's value. It will always
	// return the appropriate type for the flag (never nil).
	GetValue(snap *Snapshot) interface{}

	// GetValueDetails returns the evaluation details
	// along with the flag's value. Its Value field always
	// have the appropriate type for the flag.
	GetValueDetails(snap *Snapshot) EvaluationDetails
}

Flag is the interface implemented by all flag types.

type FlagOverrides

type FlagOverrides struct {
	// Behavior describes how the overrides should behave. Default is LocalOnly.
	Behavior OverrideBehavior

	// Values is a map that contains the overrides.
	// Each value must be one of the following types: bool, int, float64, or string.
	Values map[string]interface{}

	// FilePath is the path to a JSON file that contains the overrides.
	// The supported JSON file formats are documented here: https://configcat.com/docs/sdk-reference/go/#json-file-structure
	FilePath string
	// contains filtered or unexported fields
}

FlagOverrides describes feature flag and setting overrides. With flag overrides you can overwrite the feature flags downloaded from the ConfigCat CDN with local values.

With Values, you can set up the SDK to load your feature flag overrides from a map.

With FilePath, you can set up the SDK to load your feature flag overrides from a JSON file.

type FloatEvaluationDetails

type FloatEvaluationDetails struct {
	Data  EvaluationDetailsData
	Value float64
}

FloatEvaluationDetails holds the additional evaluation information along with the value of a decimal number flag.

type FloatFlag

type FloatFlag struct {
	// contains filtered or unexported fields
}

func Float

func Float(key string, defaultValue float64) FloatFlag

Float is like Bool but for float-valued flags.

func (FloatFlag) Get

func (f FloatFlag) Get(snap *Snapshot) float64

Get reports the value of the flag with respect to the given snapshot. It returns the flag's default value if snap is nil or the key isn't in the configuration.

func (FloatFlag) GetValue

func (f FloatFlag) GetValue(snap *Snapshot) interface{}

GetValue implements Flag.GetValue.

func (FloatFlag) GetValueDetails

func (f FloatFlag) GetValueDetails(snap *Snapshot) EvaluationDetails

GetValueDetails implements Flag.GetValueDetails.

func (FloatFlag) GetWithDetails

func (f FloatFlag) GetWithDetails(snap *Snapshot) FloatEvaluationDetails

GetWithDetails returns the evaluation details along with the flag's value. It returns FloatEvaluationDetails with the flag's default value if snap is nil or the key isn't in the configuration.

func (FloatFlag) Key

func (f FloatFlag) Key() string

Key returns the name of the flag as passed to Float.

type Hooks

type Hooks struct {
	// OnFlagEvaluated is called each time when the SDK evaluates a feature flag or setting.
	OnFlagEvaluated func(details *EvaluationDetails)

	// OnError is called when an error occurs inside the ConfigCat SDK.
	OnError func(err error)

	// OnConfigChanged is called, when a new config.json has downloaded.
	OnConfigChanged func()
}

Hooks describes the events sent by Client.

type IntEvaluationDetails

type IntEvaluationDetails struct {
	Data  EvaluationDetailsData
	Value int
}

IntEvaluationDetails holds the additional evaluation information along with the value of a whole number flag.

type IntFlag

type IntFlag struct {
	// contains filtered or unexported fields
}

func Int

func Int(key string, defaultValue int) IntFlag

Int is like Bool but for int-valued flags.

func (IntFlag) Get

func (f IntFlag) Get(snap *Snapshot) int

Get reports the value of the flag with respect to the given snapshot. It returns the flag's default value if snap is nil or the key isn't in the configuration.

func (IntFlag) GetValue

func (f IntFlag) GetValue(snap *Snapshot) interface{}

GetValue implements Flag.GetValue.

func (IntFlag) GetValueDetails

func (f IntFlag) GetValueDetails(snap *Snapshot) EvaluationDetails

GetValueDetails implements Flag.GetValueDetails.

func (IntFlag) GetWithDetails

func (f IntFlag) GetWithDetails(snap *Snapshot) IntEvaluationDetails

GetWithDetails returns the evaluation details along with the flag's value. It returns IntEvaluationDetails with the flag's default value if snap is nil or the key isn't in the configuration.

func (IntFlag) Key

func (f IntFlag) Key() string

Key returns the name of the flag as passed to Int.

type LogLevel

type LogLevel int
const (
	LogLevelDebug LogLevel = -2
	LogLevelInfo  LogLevel = -1
	LogLevelWarn  LogLevel = 0
	LogLevelError LogLevel = 1
	LogLevelNone  LogLevel = 2
)

func (LogLevel) String

func (lvl LogLevel) String() string

type Logger

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

Logger defines the interface this library logs with.

func DefaultLogger

func DefaultLogger() Logger

DefaultLogger creates the default logger with specified log level.

type OverrideBehavior

type OverrideBehavior int

OverrideBehavior describes how the overrides should behave.

type PercentageOption

type PercentageOption struct {
	// Value is the served value of the percentage option.
	Value *SettingValue `json:"v"`
	// Percentage is a number between 0 and 100 that represents a randomly allocated fraction of the users.
	Percentage int64 `json:"p"`
	// VariationID of the percentage option.
	VariationID string `json:"i"`
	// contains filtered or unexported fields
}

PercentageOption represents a percentage option.

type PollingMode

type PollingMode int

PollingMode specifies a strategy for refreshing the configuration.

const (
	// AutoPoll causes the client to refresh the configuration
	// automatically at least as often as the Config.PollInterval
	// parameter.
	AutoPoll PollingMode = iota

	// Manual will only refresh the configuration when Refresh
	// is called explicitly, falling back to the cache for the initial
	// value or if the refresh fails.
	Manual

	// Lazy will refresh the configuration whenever a value
	// is retrieved and the configuration is older than
	// Config.PollInterval.
	Lazy
)

type Preferences

type Preferences struct {
	// Salt is used to hash sensitive comparison values.
	Salt     string           `json:"s"`
	URL      string           `json:"u"`
	Redirect *RedirectionKind `json:"r"` // NoRedirect, ShouldRedirect or ForceRedirect
	// contains filtered or unexported fields
}

type PrerequisiteComparator

type PrerequisiteComparator uint8

PrerequisiteComparator is the prerequisite flag comparison operator used during the evaluation process.

const (
	// OpPrerequisiteEq matches when the evaluated value of the specified prerequisite flag is equal to the comparison value.
	OpPrerequisiteEq PrerequisiteComparator = 0
	// OpPrerequisiteNotEq matches when the evaluated value of the specified prerequisite flag is not equal to the comparison value.
	OpPrerequisiteNotEq PrerequisiteComparator = 1
)

func (PrerequisiteComparator) String

func (op PrerequisiteComparator) String() string

type PrerequisiteFlagCondition

type PrerequisiteFlagCondition struct {
	// FlagKey is the key of the prerequisite flag that the condition is based on.
	FlagKey string `json:"f"`
	// Comparator is the operator which defines the relation between the evaluated value of the prerequisite flag and the comparison value.
	Comparator PrerequisiteComparator `json:"c"`
	// Value that the evaluated value of the prerequisite flag is compared to.
	Value *settingValueJson `json:"v"`
	// contains filtered or unexported fields
}

PrerequisiteFlagCondition describes a condition based on a prerequisite feature flag.

type RedirectionKind

type RedirectionKind uint8
const (
	// NoDirect indicates that the configuration is available
	// in this request, but that the next request should be
	// made to the redirected address.
	NoDirect RedirectionKind = 0

	// ShouldRedirect indicates that there is no configuration
	// available at this address, and that the client should
	// redirect immediately. This does not take effect when
	// talking to a custom URL.
	ShouldRedirect RedirectionKind = 1

	// ForceRedirect indicates that there is no configuration
	// available at this address, and that the client should redirect
	// immediately even when talking to a custom URL.
	ForceRedirect RedirectionKind = 2
)

type Segment

type Segment struct {
	// Name is the first 4 characters of the Segment's name
	Name string `json:"n"`
	// Conditions is the list of segment rule conditions (has a logical AND relation between the items).
	Conditions []*UserCondition `json:"r"`
	// contains filtered or unexported fields
}

Segment describes a ConfigCat segment.

type SegmentComparator

type SegmentComparator uint8

SegmentComparator is the segment comparison operator used during the evaluation process.

const (
	// OpSegmentIsIn matches when the conditions of the specified segment are evaluated to true.
	OpSegmentIsIn SegmentComparator = 0
	// OpSegmentIsNotIn matches when the conditions of the specified segment are evaluated to false.
	OpSegmentIsNotIn SegmentComparator = 1
)

func (SegmentComparator) String

func (op SegmentComparator) String() string

type SegmentCondition

type SegmentCondition struct {
	// Index identifies the segment that the condition is based on.
	Index int `json:"s"`
	// Comparator is the operator which defines the expected result of the evaluation of the segment.
	Comparator SegmentComparator `json:"c"`
	// contains filtered or unexported fields
}

SegmentCondition describes a condition based on a segment.

type ServedValue

type ServedValue struct {
	// Value is the value associated with the targeting rule or nil if the targeting rule has percentage options THEN part.
	Value *SettingValue `json:"v"`
	// VariationID of the targeting rule.
	VariationID string `json:"i"`
	// contains filtered or unexported fields
}

type Setting

type Setting struct {
	// PercentageOptionsAttribute is the User Object attribute which serves as the basis of percentage options evaluation.
	PercentageOptionsAttribute string `json:"a"`
	// VariationID is the variation ID.
	VariationID string `json:"i"`
	// Value holds the setting's default value used when no targeting rules are matching during an evaluation process.
	Value *SettingValue `json:"v"`
	// Type describes the setting's type. It can be BoolSetting, StringSetting, IntSetting, FloatSetting
	Type SettingType `json:"t"`
	// TargetingRules is the list of targeting rules (where there is a logical OR relation between the items).
	TargetingRules []*TargetingRule `json:"r"`
	// PercentageOptions is the list of percentage options.
	PercentageOptions []*PercentageOption `json:"p"`
	// contains filtered or unexported fields
}

Setting describes a feature flag or setting.

type SettingType

type SettingType int8
const (
	UnknownSetting SettingType = -1
	// BoolSetting is the On/off type (feature flag).
	BoolSetting SettingType = 0
	// StringSetting represents a text setting.
	StringSetting SettingType = 1
	// IntSetting is the whole number type.
	IntSetting SettingType = 2
	// FloatSetting is the decimal number type.
	FloatSetting SettingType = 3
)

type SettingValue

type SettingValue struct {
	// Value holds the feature flag's value.
	Value interface{}
	// contains filtered or unexported fields
}

SettingValue describes the value of a feature flag or setting.

func (*SettingValue) MarshalJSON

func (s *SettingValue) MarshalJSON() ([]byte, error)

func (*SettingValue) UnmarshalJSON

func (s *SettingValue) UnmarshalJSON(b []byte) error

type SimplifiedConfig

type SimplifiedConfig struct {
	Flags map[string]interface{} `json:"flags"`
}

type Snapshot

type Snapshot struct {
	// contains filtered or unexported fields
}

Snapshot holds a snapshot of the ConfigCat configuration. A snapshot is immutable once taken.

A nil snapshot is OK to use and acts like a configuration with no keys.

func NewSnapshot

func NewSnapshot(logger Logger, values map[string]interface{}) (*Snapshot, error)

NewSnapshot returns a snapshot that always returns the given values.

Each entry in the values map is keyed by a flag name and holds the value that the snapshot will return for that flag. Each value must be one of the types bool, int, float64, or string.

The returned snapshot does not support variation IDs. That is, given a snapshot s returned by NewSnapshot: - s.GetKeyValueForVariationID returns "", nil. - s.GetVariationID returns "". - s.GetVariationIDs returns nil.

func (*Snapshot) FetchTime

func (snap *Snapshot) FetchTime() time.Time

func (*Snapshot) GetAllKeys

func (snap *Snapshot) GetAllKeys() []string

GetAllKeys returns all the known keys in arbitrary order.

func (*Snapshot) GetAllValueDetails

func (snap *Snapshot) GetAllValueDetails() []EvaluationDetails

GetAllValueDetails returns values along with evaluation details of all feature flags and settings.

func (*Snapshot) GetAllValues

func (snap *Snapshot) GetAllValues() map[string]interface{}

GetAllValues returns all keys and values in freshly allocated key-value map.

func (*Snapshot) GetKeyValueForVariationID

func (snap *Snapshot) GetKeyValueForVariationID(id string) (string, interface{})

GetKeyValueForVariationID returns the key and value that are associated with the given variation ID. If the variation ID isn't found, it returns "", nil.

func (*Snapshot) GetValue

func (snap *Snapshot) GetValue(key string) interface{}

GetValue returns a feature flag value regardless of type. If there is no value found, it returns nil; otherwise the returned value has one of the dynamic types bool, int, float64, or string.

To use obtain the value of a typed feature flag, use one of the typed feature flag functions. For example:

someFlag := configcat.Bool("someFlag", false)
value := someFlag.Get(snap)

func (*Snapshot) GetValueDetails

func (snap *Snapshot) GetValueDetails(key string) EvaluationDetails

GetValueDetails returns the value and evaluation details of a feature flag or setting with respect to the current user, or nil if none is found.

func (*Snapshot) WithUser

func (snap *Snapshot) WithUser(user User) *Snapshot

WithUser returns a copy of s associated with the given user. If snap is nil, it returns nil. If user is nil, it uses Config.DefaultUser.

type StringEvaluationDetails

type StringEvaluationDetails struct {
	Data  EvaluationDetailsData
	Value string
}

StringEvaluationDetails holds the additional evaluation information along with the value of a string flag.

type StringFlag

type StringFlag struct {
	// contains filtered or unexported fields
}

func String

func String(key string, defaultValue string) StringFlag

String is like Bool but for string-valued flags.

func (StringFlag) Get

func (f StringFlag) Get(snap *Snapshot) string

Get reports the value of the flag with respect to the given snapshot. It returns the flag's default value if snap is nil or the key isn't in the configuration.

func (StringFlag) GetValue

func (f StringFlag) GetValue(snap *Snapshot) interface{}

GetValue implements Flag.GetValue.

func (StringFlag) GetValueDetails

func (f StringFlag) GetValueDetails(snap *Snapshot) EvaluationDetails

GetValueDetails implements Flag.GetValueDetails.

func (StringFlag) GetWithDetails

func (f StringFlag) GetWithDetails(snap *Snapshot) StringEvaluationDetails

GetWithDetails returns the evaluation details along with the flag's value. It returns StringEvaluationDetails with the flag's default value if snap is nil or the key isn't in the configuration.

func (StringFlag) Key

func (f StringFlag) Key() string

Key returns the name of the flag as passed to String.

type TargetingRule

type TargetingRule struct {
	// ServedValue is the value associated with the targeting rule or nil if the targeting rule has percentage options THEN part.
	ServedValue *ServedValue `json:"s"`
	// Conditions is the list of conditions that are combined with the AND logical operator.
	Conditions []*Condition `json:"c"`
	// PercentageOptions is the list of percentage options associated with the targeting rule or nil if the targeting rule has a served value THEN part.
	PercentageOptions []*PercentageOption `json:"p"`
}

TargetingRule represents a targeting rule used in the flag evaluation process.

type User

type User interface{}

The User interface represents the user-specific data that can influence feature flag rule evaluation. All Users are expected to provide an Identifier attribute. A User value is assumed to be immutable once it's been provided to the SDK - if it changes between feature flag evaluations, there's no guarantee that the feature flag results will change accordingly (use WithUser instead of mutating the value).

The ConfigCat client uses reflection to determine what attributes are available:

If the User value implements UserAttributes, then that method will be used to retrieve attributes.

Otherwise, the implementation is expected to be a pointer to a struct type. Each public field in the struct is treated as a possible comparison attribute.

If a field's type is map[string]interface{}, the map value 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 type, []string type, a []byte type, a time.Time type, or a github.com/blang/semver.Version.

If a rule uses an attribute that isn't available, that rule will be treated as non-matching.

type UserAttributes

type UserAttributes interface {
	GetAttribute(attr string) interface{}
}

UserAttributes can be implemented by a User value to implement support for getting arbitrary attributes.

type UserCondition

type UserCondition struct {
	// ComparisonAttribute is a User Object attribute that the condition is based on. Can be "Identifier", "Email", "Country" or any custom attribute.
	ComparisonAttribute string `json:"a"`
	// StringValue is a value in text format that the User Object attribute is compared to.
	StringValue *string `json:"s"`
	// DoubleValue is a value in numeric format that the User Object attribute is compared to.
	DoubleValue *float64 `json:"d"`
	// StringArrayValue is a value in text array format that the User Object attribute is compared to.
	StringArrayValue []string `json:"l"`
	// Comparator is the operator which defines the relation between the comparison attribute and the comparison value.
	Comparator Comparator `json:"c"`
}

UserCondition describes a condition based on User Object attributes

type UserData

type UserData struct {
	Identifier string
	Email      string
	Country    string
	Custom     map[string]interface{}
}

UserData implements the User interface with the basic set of attributes. For an efficient way to use your own domain object as a User, see the documentation for the User interface.

Directories

Path Synopsis
Package configcatcache holds utility functions for the SDK's caching.
Package configcatcache holds utility functions for the SDK's caching.
Package configcattest provides an HTTP handler that can be used to test configcat scenarios in tests.
Package configcattest provides an HTTP handler that can be used to test configcat scenarios in tests.
samples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL