configcat

package module
v7.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2022 License: MIT Imports: 20 Imported by: 4

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 codecov GoDoc License

Getting started

1. Install the package with go
go get github.com/configcat/go-sdk/v7
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/v7"
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

ConfigCat SDK for Go (https://configcat.com)

Index

Constants

View Source
const (
	LogLevelPanic = logrus.PanicLevel
	LogLevelFatal = logrus.FatalLevel
	LogLevelError = logrus.ErrorLevel
	LogLevelWarn  = logrus.WarnLevel
	LogLevelInfo  = logrus.InfoLevel
	LogLevelDebug = logrus.DebugLevel
	LogLevelTrace = logrus.TraceLevel
)

Define the logrus log levels

View Source
const DefaultPollInterval = 60 * time.Second

Variables

This section is empty.

Functions

This section is empty.

Types

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 added in v7.3.0

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

GetValue implements Flag.GetValue.

func (BoolFlag) Key added in v7.2.0

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) 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) 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) 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) 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) GetVariationID

func (client *Client) GetVariationID(key string, defaultVariationId string, user User) string

GetVariationID returns the variation ID (analytics) that will be used for the given key with respect to the given user, or the default value if none is found.

func (*Client) GetVariationIDs

func (client *Client) GetVariationIDs(user User) []string

GetVariationIDs returns all variation IDs (analytics) in the current configuration that apply to the given user, or Config.DefaultUser if user is nil.

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) Snapshot

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

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

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(LogLevelWarn) will be used.
	// It assumes that the logging level will not be increased
	// during the lifetime of the client.
	Logger Logger

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

	// ChangeNotify is called, if not nil, when the settings configuration
	// has changed.
	ChangeNotify func()

	// 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
}

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 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 Flag added in v7.3.0

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{}
}

Flag is the interface implemented by all flag types.

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 added in v7.3.0

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

GetValue implements Flag.GetValue.

func (FloatFlag) Key added in v7.2.0

func (f FloatFlag) Key() string

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

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 added in v7.3.0

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

GetValue implements Flag.GetValue.

func (IntFlag) Key added in v7.2.0

func (f IntFlag) Key() string

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

type LogLevel

type LogLevel = logrus.Level

type Logger

type Logger interface {
	// GetLevel returns the current logging level.
	GetLevel() LogLevel

	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(level LogLevel) Logger

DefaultLogger creates the default logger with specified log level (logrus.New()).

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 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 added in v7.1.0

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) GetAllKeys

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

GetAllKeys returns all the known keys in arbitrary order.

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) GetVariationID

func (snap *Snapshot) GetVariationID(key string) string

GetVariationID returns the variation ID that will be used for the given key with respect to the current user, or the empty string if none is found.

func (*Snapshot) GetVariationIDs

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

GetVariationIDs returns all variation IDs in the current configuration that apply to the current user.

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 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 added in v7.3.0

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

GetValue implements Flag.GetValue.

func (StringFlag) Key added in v7.2.0

func (f StringFlag) Key() string

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

type User

type User interface{}

The User interface represents the user-specific data that can influence configcat 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 configcat - 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 implements a `String() string` method, the field will be treated as a textual and the String method will be called to determine the value.

If a field's type is map[string] string, 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, a []byte 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) string
}

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

type UserData

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

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 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.
internal
wireconfig
Package wireconfig holds types and constants that define the representation of the ConfigCat configuration as transmitted over the wire from the ConfigCat CDN.
Package wireconfig holds types and constants that define the representation of the ConfigCat configuration as transmitted over the wire from the ConfigCat CDN.

Jump to

Keyboard shortcuts

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