configcat

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2019 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 Management Console 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 gopkg.in/configcat/go-sdk.v1
2. Go to Connect your application tab to get your API Key:

API-KEY

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

Or use the async APIs:

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.

Support

If you need help how to use this SDK feel free to to contact the ConfigCat Staff on https://configcat.com. We're happy to help.

Contributing

Contributions are welcome.

About ConfigCat

Documentation

Overview

Package configcat contains the Golang SDK for ConfigCat (https://configcat.com)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewInMemoryConfigCache

func NewInMemoryConfigCache() *inMemoryConfigCache

NewInMemoryConfigCache creates an in-memory cache implementation used to store the fetched configurations.

Types

type Async

type Async struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Async describes an object which used to control asynchronous operations. Usage:

async := NewAsync()
async.Accept(func() {
   fmt.Print("operation completed")
}).Accept(func() {
   fmt.Print("chained operation completed")
})
go func() { async.Complete() }()

func NewAsync

func NewAsync() *Async

NewAsync initializes a new async object.

func (*Async) Accept

func (async *Async) Accept(completion func()) *Async

Accept allows the chaining of the async operations after each other and subscribes a simple a callback function called when the async operation completed. For example:

async.Accept(func() {
   fmt.Print("operation completed")
})

func (*Async) Apply

func (async *Async) Apply(completion func() interface{}) *AsyncResult

Apply allows the chaining of the async operations after each other and subscribes a callback function which called when the async operation completed. Returns an AsyncResult object which returns a result. For example:

async.Apply(func() {
   return "new result"
})

func (*Async) Complete

func (async *Async) Complete()

Complete moves the async operation into the completed state.

func (*Async) IsCompleted

func (async *Async) IsCompleted() bool

IsCompleted returns true if the async operation is marked as completed, otherwise false.

func (*Async) IsPending

func (async *Async) IsPending() bool

IsPending returns true if the async operation is running, otherwise false.

func (*Async) Wait

func (async *Async) Wait()

Wait blocks until the async operation is completed.

func (*Async) WaitOrTimeout

func (async *Async) WaitOrTimeout(duration time.Duration) error

WaitOrTimeout blocks until the async operation is completed or until the given timeout duration expires.

type AsyncResult

type AsyncResult struct {
	*Async
	sync.RWMutex
	// contains filtered or unexported fields
}

AsyncResult describes an object which used to control asynchronous operations with return value. Allows the chaining of these operations after each other. Usage:

 async := NewAsync()
 async.ApplyThen(func(result interface{}) {
	   fmt.Print(result)
    return "new result"
 }).Apply(func(previousResult interface{}) {
    fmt.Print("chained operation completed")
 })
 go func() { async.Complete("success") }()

func AsCompletedAsyncResult

func AsCompletedAsyncResult(result interface{}) *AsyncResult

AsCompletedAsyncResult creates an already completed async object.

func NewAsyncResult

func NewAsyncResult() *AsyncResult

NewAsyncResult initializes a new async object with result.

func (*AsyncResult) Accept

func (asyncResult *AsyncResult) Accept(completion func(result interface{})) *Async

Accept allows the chaining of the async operations after each other and subscribes a callback function which gets the operation result as argument and called when the async operation completed. Returns an Async object. For example:

async.Accept(func(result interface{}) {
   fmt.Print(result)
})

func (*AsyncResult) ApplyThen

func (asyncResult *AsyncResult) ApplyThen(completion func(result interface{}) interface{}) *AsyncResult

ApplyThen allows the chaining of the async operations after each other and subscribes a callback function which gets the operation result as argument and called when the async operation completed. Returns an AsyncResult object which returns a different result type. For example:

async.Accept(func(result interface{}) {
   fmt.Print(result)
})

func (*AsyncResult) Complete

func (asyncResult *AsyncResult) Complete(result interface{})

Complete moves the async operation into the completed state. Gets the result of the operation as argument.

func (*AsyncResult) Get

func (asyncResult *AsyncResult) Get() interface{}

Get blocks until the async operation is completed, then returns the result of the operation.

func (*AsyncResult) GetOrTimeout

func (asyncResult *AsyncResult) GetOrTimeout(duration time.Duration) (interface{}, error)

GetOrTimeout blocks until the async operation is completed or until the given timeout duration expires, then returns the result of the operation.

type AutoPollingPolicy

type AutoPollingPolicy struct {
	ConfigRefresher
	// contains filtered or unexported fields
}

AutoPollingPolicy describes a RefreshPolicy which polls the latest configuration over HTTP and updates the local cache repeatedly.

func NewAutoPollingPolicy

func NewAutoPollingPolicy(
	configProvider ConfigProvider,
	store *ConfigStore,
	autoPollInterval time.Duration) *AutoPollingPolicy

NewAutoPollingPolicy initializes a new AutoPollingPolicy.

func NewAutoPollingPolicyWithChangeListener

func NewAutoPollingPolicyWithChangeListener(
	configProvider ConfigProvider,
	store *ConfigStore,
	autoPollInterval time.Duration,
	configChanged func(config string, parser *ConfigParser)) *AutoPollingPolicy

NewAutoPollingPolicyWithChangeListener initializes a new AutoPollingPolicy. An optional configuration change listener callback can be passed.

func (*AutoPollingPolicy) Close

func (policy *AutoPollingPolicy) Close()

Close shuts down the policy.

func (*AutoPollingPolicy) GetConfigurationAsync

func (policy *AutoPollingPolicy) GetConfigurationAsync() *AsyncResult

GetConfigurationAsync reads the current configuration value.

type Client

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

Client is an object for handling configurations provided by ConfigCat.

func NewClient

func NewClient(apiKey string) *Client

NewClient initializes a new ConfigCat Client with the default configuration. The api key parameter is mandatory.

func NewCustomClient

func NewCustomClient(apiKey string, config ClientConfig) *Client

NewCustomClient initializes a new ConfigCat Client with advanced configuration. The api key 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 added in v1.2.0

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

GetAllKeys retrieves all the setting keys.

func (*Client) GetAllKeysAsync added in v1.2.0

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

GetAllKeysAsync retrieves all the setting keys asynchronously.

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) 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 {
	// Base logger used to create new loggers
	Logger Logger
	// The factory delegate used to produce custom RefreshPolicy implementations.
	PolicyFactory func(configProvider ConfigProvider, store *ConfigStore) RefreshPolicy
	// 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
}

ClientConfig describes custom configuration options for the Client.

func DefaultClientConfig

func DefaultClientConfig() ClientConfig

DefaultClientConfig prepares a default configuration for the ConfigCat Client.

type ConfigCache

type ConfigCache interface {
	// Get reads the configuration from the cache.
	Get() (string, error)
	// Set writes the configuration into the cache.
	Set(value string) error
}

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

type ConfigFetcher

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

ConfigFetcher used to fetch the actual configuration over HTTP.

func (*ConfigFetcher) GetConfigurationAsync

func (fetcher *ConfigFetcher) GetConfigurationAsync() *AsyncResult

GetConfigurationAsync collects the actual configuration over HTTP.

type ConfigParser

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

ConfigParser describes a JSON configuration parser

func (*ConfigParser) GetAllKeys added in v1.2.0

func (parser *ConfigParser) GetAllKeys(jsonBody string) ([]string, error)

GetAllKeys retrieves all the setting keys from the given json config.

func (*ConfigParser) Parse

func (parser *ConfigParser) Parse(jsonBody string, key string) (interface{}, error)

Parse converts a json element identified by a key from the given json string into an interface{} value.

func (*ConfigParser) ParseWithUser

func (parser *ConfigParser) ParseWithUser(jsonBody string, key string, user *User) (interface{}, error)

ParseWithUser converts a json element identified by the key from the given json string into an interface{} value. Optional user argument can be passed to identify the caller.

type ConfigProvider

type ConfigProvider interface {
	// GetConfigurationAsync collects the actual configuration.
	GetConfigurationAsync() *AsyncResult
}

ConfigProvider describes a configuration provider which used to collect the actual configuration.

type ConfigRefresher

type ConfigRefresher struct {
	// The configuration provider implementation used to collect the latest configuration.
	ConfigProvider ConfigProvider
	// The configuration store used to maintain the cached configuration.
	Store *ConfigStore
}

ConfigRefresher describes a configuration refresher, holds a shared implementation of the RefreshAsync method on RefreshPolicy.

func (*ConfigRefresher) RefreshAsync

func (refresher *ConfigRefresher) RefreshAsync() *Async

RefreshAsync initiates a force refresh on the cached configuration.

type ConfigStore

type ConfigStore struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

ConfigStore is used to maintain the cached configuration.

func (*ConfigStore) Get

func (store *ConfigStore) Get() string

Get reads the configuration.

func (*ConfigStore) Set

func (store *ConfigStore) Set(value string)

Set writes the configuration.

type FetchResponse

type FetchResponse struct {
	Status FetchStatus
	Body   string
}

FetchResponse represents a configuration fetch response.

func (FetchResponse) IsFailed

func (response FetchResponse) IsFailed() bool

IsFailed returns true if the fetch is failed, otherwise false.

func (FetchResponse) IsFetched

func (response FetchResponse) IsFetched() bool

IsFetched returns true if a new configuration value was fetched, otherwise false.

func (FetchResponse) IsNotModified

func (response FetchResponse) IsNotModified() bool

IsNotModified returns true if if the fetch resulted a 304 Not Modified code, otherwise false.

type FetchStatus

type FetchStatus int

FetchStatus describes the fetch response statuses.

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
)

type LazyLoadingPolicy

type LazyLoadingPolicy struct {
	ConfigRefresher
	// contains filtered or unexported fields
}

LazyLoadingPolicy describes a RefreshPolicy which uses an expiring cache to maintain the internally stored configuration.

func NewLazyLoadingPolicy

func NewLazyLoadingPolicy(
	configProvider ConfigProvider,
	store *ConfigStore,
	cacheInterval time.Duration,
	useAsyncRefresh bool) *LazyLoadingPolicy

NewLazyLoadingPolicy initializes a new LazyLoadingPolicy.

func (*LazyLoadingPolicy) Close

func (policy *LazyLoadingPolicy) Close()

Close shuts down the policy.

func (*LazyLoadingPolicy) GetConfigurationAsync

func (policy *LazyLoadingPolicy) GetConfigurationAsync() *AsyncResult

GetConfigurationAsync reads the current configuration value.

type Logger added in v1.3.0

type Logger interface {
	Prefix(string) Logger

	Print(...interface{})
	Printf(string, ...interface{})
}

Logger defines the interface this library logs with

func DefaultLogger added in v1.3.0

func DefaultLogger(name string) Logger

DefaultLogger instantiates a default logger backed by the standard library logger

type ManualPollingPolicy

type ManualPollingPolicy struct {
	ConfigRefresher
}

ManualPollingPolicy describes a RefreshPolicy which fetches the latest configuration over HTTP every time when a get configuration is called.

func NewManualPollingPolicy

func NewManualPollingPolicy(
	configProvider ConfigProvider,
	store *ConfigStore) *ManualPollingPolicy

NewManualPollingPolicy initializes a new ManualPollingPolicy.

func (*ManualPollingPolicy) Close

func (policy *ManualPollingPolicy) Close()

Close shuts down the policy.

func (*ManualPollingPolicy) GetConfigurationAsync

func (policy *ManualPollingPolicy) GetConfigurationAsync() *AsyncResult

GetConfigurationAsync reads the current configuration value.

type ParseError

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

ParseError describes JSON parsing related errors

func (*ParseError) Error

func (p *ParseError) Error() string

Error is the error message

type RefreshPolicy

type RefreshPolicy interface {
	// GetConfigurationAsync reads the current configuration value.
	GetConfigurationAsync() *AsyncResult
	// RefreshAsync initiates a force refresh on the cached configuration.
	RefreshAsync() *Async
	// Close shuts down the policy.
	Close()
}

RefreshPolicy is the public interface of a refresh policy which's implementors should describe the configuration update rules.

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 added in v1.4.0

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

Directories

Path Synopsis
samples

Jump to

Keyboard shortcuts

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