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

About ConfigCat

Expand ▾ Collapse ▴

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

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

                    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 current 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.

                                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

                                    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
                                    }

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

                                            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

                                              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 (*Snapshot) GetAllKeys

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

                                                        GetAllKeys returns all the known keys.

                                                        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.

                                                                  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

                                                                    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.

                                                                      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.