configcat

package module
v6.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2020 License: MIT Imports: 14 Imported by: 0

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/v6
2. Go to Connect your application tab to get your SDK Key:

SDK-KEY

3. Import the ConfigCat client package to your application
import "github.com/configcat/go-sdk/v6"
4. Create a ConfigCat client instance:
client := configcat.NewClient("#YOUR-SDK-KEY#")
5. Get your setting value:
isMyAwesomeFeatureEnabled, ok := client.GetValue("isMyAwesomeFeatureEnabled", false).(bool)
if ok && isMyAwesomeFeatureEnabled {
    DoTheNewThing()
} else {
    DoTheOldThing()
}

Or use the async SDKs:

client.GetValueAsync("isMyAwesomeFeatureEnabled", false, func(result interface{}) {
    isMyAwesomeFeatureEnabled, ok := result.(bool)
    if ok && 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 User Object to the getValue() function.

Read more about Targeting here.

user := configcat.NewUser("#USER-IDENTIFIER#")

isMyAwesomeFeatureEnabled, ok := client.GetValueForUser("isMyAwesomeFeatureEnabled", user, false).(bool)
if ok && 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.

About ConfigCat

Documentation

Overview

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

Index

Constants

View Source
const (
	ConfigJsonName = "config_v5"

	NoRedirect     = 0
	ShouldRedirect = 1
	ForceRedirect  = 2
)
View Source
const (
	// Fetched indicates that a new configuration was fetched.
	Fetched fetchStatus = 0
	// NotModified indicates that the current configuration is not modified.
	NotModified fetchStatus = 1
	// Failure indicates that the current configuration fetch is failed.
	Failure fetchStatus = 2
)
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 CacheBase = "go_" + ConfigJsonName + "_%s"

Variables

This section is empty.

Functions

This section is empty.

Types

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 initializes a new ConfigCat Client with the default configuration. The sdkKey parameter is mandatory.

func NewCustomClient

func NewCustomClient(sdkKey string, config ClientConfig) *Client

NewCustomClient initializes a new ConfigCat Client with advanced configuration. The sdkKey parameter is mandatory.

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, error)

GetAllKeys retrieves all the setting keys.

func (*Client) GetAllKeysAsync

func (client *Client) GetAllKeysAsync(completion func(result []string, err error))

GetAllKeysAsync retrieves all the setting keys asynchronously.

func (*Client) GetAllVariationIds

func (client *Client) GetAllVariationIds() ([]string, error)

GetAllVariationIds returns the Variation IDs synchronously as []string from the configuration.

func (*Client) GetAllVariationIdsAsync

func (client *Client) GetAllVariationIdsAsync(completion func(result []string, err error))

GetAllVariationIdsAsync reads and sends a Variation ID asynchronously to a callback function as []string from the configuration.

func (*Client) GetAllVariationIdsAsyncForUser

func (client *Client) GetAllVariationIdsAsyncForUser(user *User, completion func(result []string, err error))

GetAllVariationIdsAsyncForUser reads and sends a Variation ID asynchronously to a callback function as []string from the configuration. Optional user argument can be passed to identify the caller.

func (*Client) GetAllVariationIdsForUser

func (client *Client) GetAllVariationIdsForUser(user *User) ([]string, error)

GetAllVariationIdsForUser returns the Variation IDs synchronously as []string from the configuration. Optional user argument can be passed to identify the caller.

func (*Client) GetKeyAndValue

func (client *Client) GetKeyAndValue(variationId string) (string, interface{})

GetKeyAndValue returns the key of a setting and its value identified by the given Variation ID.

func (*Client) GetKeyAndValueAsync

func (client *Client) GetKeyAndValueAsync(variationId string, completion func(key string, value interface{}))

GetAllVariationIdsAsyncForUser reads and sends the key of a setting and its value identified by the given Variation ID asynchronously to a callback function as (string, interface{}) from the configuration.

func (*Client) GetValue

func (client *Client) GetValue(key string, defaultValue interface{}) interface{}

GetValue returns a value synchronously as interface{} from the configuration identified by the given key.

func (*Client) GetValueAsync

func (client *Client) GetValueAsync(key string, defaultValue interface{}, completion func(result interface{}))

GetValueAsync reads and sends a value asynchronously to a callback function as interface{} from the configuration identified by the given key.

func (*Client) GetValueAsyncForUser

func (client *Client) GetValueAsyncForUser(key string, defaultValue interface{}, user *User, completion func(result interface{}))

GetValueAsyncForUser reads and sends a value asynchronously to a callback function as interface{} from the configuration identified by the given key. Optional user argument can be passed to identify the caller.

func (*Client) GetValueForUser

func (client *Client) GetValueForUser(key string, defaultValue interface{}, user *User) interface{}

GetValueForUser returns a value synchronously as interface{} from the configuration identified by the given key. Optional user argument can be passed to identify the caller.

func (*Client) GetVariationId

func (client *Client) GetVariationId(key string, defaultVariationId string) string

GetVariationId returns a Variation ID synchronously as string from the configuration identified by the given key.

func (*Client) GetVariationIdAsync

func (client *Client) GetVariationIdAsync(key string, defaultVariationId string, completion func(result string))

GetVariationIdAsync reads and sends a Variation ID asynchronously to a callback function as string from the configuration identified by the given key.

func (*Client) GetVariationIdAsyncForUser

func (client *Client) GetVariationIdAsyncForUser(key string, defaultVariationId string, user *User, completion func(result string))

GetVariationIdAsyncForUser reads and sends a Variation Id asynchronously to a callback function as string from the configuration identified by the given key. Optional user argument can be passed to identify the caller.

func (*Client) GetVariationIdForUser

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

GetVariationIdForUser returns a Variation ID synchronously as string from the configuration identified by the given key. Optional user argument can be passed to identify the caller.

func (*Client) Refresh

func (client *Client) Refresh()

Refresh initiates a force refresh synchronously on the cached configuration.

func (*Client) RefreshAsync

func (client *Client) RefreshAsync(completion func())

RefreshAsync initiates a force refresh asynchronously on the cached configuration.

type ClientConfig

type ClientConfig struct {
	// Logger is used to log information about configuration evaluation
	// and issues.
	Logger Logger
	// StaticLogLevel specifies whether the log level will remain the
	// same throughout the lifetime of the client.
	// If this is true and Logger implements the LoggerWithLevel
	// interface (notably, the default logger, *logrus.Logger, implements this interface),
	// the client can use a more efficient log implementation.
	StaticLogLevel bool
	// The custom cache implementation used to store the configuration.
	Cache ConfigCache
	// The maximum time how long at most the synchronous calls (e.g. client.get(...)) should block the caller.
	// If it's 0 then the caller will be blocked in case of sync calls, until the operation succeeds or fails.
	MaxWaitTimeForSyncCalls time.Duration
	// The maximum wait time for a http response.
	HttpTimeout time.Duration
	// The base ConfigCat CDN url.
	BaseUrl string
	// The custom http transport object.
	Transport http.RoundTripper
	// The refresh mode of the cached configuration.
	Mode RefreshMode
	// Default: Global. Set this parameter to be in sync with the Data Governance preference on the Dashboard:
	// https://app.configcat.com/organization/data-governance (Only Organization Admins have access)
	DataGovernance DataGovernance
}

ClientConfig describes custom configuration options for the Client.

type ConfigCache

type ConfigCache interface {
	// get reads the configuration from the cache.
	Get(key string) (string, error)
	// set writes the configuration into the cache.
	Set(key string, value string) 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 LogLevel

type LogLevel = logrus.Level

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

	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})

	Debugln(args ...interface{})
	Infoln(args ...interface{})
	Warnln(args ...interface{})
	Errorln(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 LoggerWithLevel added in v6.1.0

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

LoggerWithLevel is optionally implemented by a Logger. It is notably implemented by logrus.Logger and thus by the DefaultLogger returned by this package.

type RefreshMode

type RefreshMode interface {
	// contains filtered or unexported methods
}

func AutoPoll

func AutoPoll(interval time.Duration) RefreshMode

AutoPoll creates an auto polling refresh mode that polls for changes at the given interval.

func AutoPollWithChangeListener

func AutoPollWithChangeListener(
	interval time.Duration,
	changeNotify func(),
) RefreshMode

AutoPollWithChangeListener creates an auto polling refresh mode. It polls for changes at the given interval, and calls changeNotify whenever the configuration has changed.

If changeNotify is nil, this is equvalent to AutoPoll.

func LazyLoad

func LazyLoad(cacheInterval time.Duration, useAsyncRefresh bool) RefreshMode

LazyLoad creates a lazy loading refresh mode. The configuration is fetched on demand the first time it's needed and then when the previous fetch is more than cacheInterval earlier. If useAsyncRefresh is true, the previous configuration will continue to be used while the configuration is refreshing rather than waiting for the new configuration to be received.

func ManualPoll

func ManualPoll() RefreshMode

ManualPoll creates a manual loading refresh mode which fetches the latest configuration only when explicitly refreshed. It uses the cache if a configuration hasn't been fetched.

type User

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

User is an object containing attributes to properly identify a given user for rollout evaluation.

func NewUser

func NewUser(identifier string) *User

NewUser creates a new user object. The identifier argument is mandatory.

func NewUserWithAdditionalAttributes

func NewUserWithAdditionalAttributes(identifier string, email string, country string, custom map[string]string) *User

NewUserWithAdditionalAttributes creates a new user object with additional attributes. The identifier argument is mandatory.

func (*User) GetAttribute

func (user *User) GetAttribute(key string) string

GetAttribute retrieves a user attribute identified by a key.

Jump to

Keyboard shortcuts

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