ffclient

package module
v1.40.0 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2024 License: MIT Imports: 22 Imported by: 33

README

go-feature-flag logo

🎛️ GO Feature Flag

Build Status Sonarcloud Status Build Status License
Release version GoDoc Go version Mentioned in Awesome Go Join us on slack Sponsords

🙏 If you are using GO Feature Flag please consider to add yourself in the adopters list.
This simple act significantly boosts the project's visibility and credibility, making a substantial contribution to its advancement.

If you want to support me and GO Feature Flag, you can also become a sponsor.

Table of Contents

What is GO Feature Flag?

GO Feature Flag is a lightweight and open-source solution that provides a simple and complete feature flag implementation.

The solution has been built to facilitate the usage of feature flags in your code with the easiest setup possible.

Originally, GO Feature Flag was designed as a solution exclusively for the GO language. With the new standardization of feature flags by the Openfeature project, the solution is now available for multiple languages (list of supported languages) through a simple API server called the relay proxy, which can be hosted.

[!TIP] If you are not familiar with feature flags, I've written an article which explains why feature flags can fasten your iteration cycle.

What can I do with GO Feature Flag?

  • Storing your configuration flags file on various locations (HTTP, S3, Kubernetes, see full list).
  • Configuring your flags in various format (JSON, TOML and YAML).
  • Adding complex rules to target your users.
  • Use a complex rollout strategy for your flags :
  • Exporting your flags usage data to various destinations such as (S3, Google cloud storage, file, see the full list).
  • Getting notified when a flag has been changed (webhook and slack).
  • Use GO Feature Flag in several languages with Open Feature SDKs.
  • Support your full stack, from the backend to the frontend including your mobile apps.

https://user-images.githubusercontent.com/17908063/211581747-f6354a9d-8be6-4e52-aa53-7f0d6a40827e.mp4

The code of this demo is available in examples/demo repository.

Getting started

[!IMPORTANT] Before starting to use GO Feature Flag you should decide if you want to use Open Feature SDKs or if you want to use GO Feature Flag as a GO Module.

We recommend using the relay-proxy for a central flag management and evaluation solution, it enables the multi-languages support, and it integrates seamlessly with the Open Feature SDKs.
This is the best way to get full potential of GO Feature Flag.

If your project is exclusively in GO, the GO module is an option. It will perform the flag evaluation directly in your GO code.

Using Open Feature SDKs
Create a feature flag configuration

Create a new YAML file containing your first flag configuration.

# 20% of the users will use the variation "my-new-feature"
test-flag:
  variations:
    my-new-feature: true
    my-old-feature: false
  defaultRule:
    percentage:
      my-new-feature: 20
      my-old-feature: 80

This flag split the usage of this flag, 20% will use the variation my-new-feature and 80% the variation my-old-feature.

Create a relay proxy configuration file

Create a new YAML file containing the configuration of your relay proxy.

listen: 1031
pollingInterval: 1000
startWithRetrieverError: false
retriever:
  kind: file
  path: /goff/flag-config.yaml
exporter:
  kind: log
Install the relay proxy

And we will run the relay proxy locally to make the API available.
The default port will be 1031.

# Launch the container
docker run \
  -p 1031:1031 \
  -v $(pwd)/flag-config.yaml:/goff/flag-config.yaml \
  -v $(pwd)/goff-proxy.yaml:/goff/goff-proxy.yaml \
  gofeatureflag/go-feature-flag:latest

If you don't want to use docker to install the relay proxy you can follow other ways to install it in the documentation.

Use Open Feature SDK

In this example, we are using the nodejs SDK, but you can check other languages here.

Install dependencies
npm i @openfeature/server-sdk @openfeature/go-feature-flag-provider
Init your Open Feature client

In your app initialization, you have to create a client using the Open Feature SDK and initialize it.

const {OpenFeature} = require("@openfeature/server-sdk");
const {GoFeatureFlagProvider} = require("@openfeature/go-feature-flag-provider");


// init Open Feature SDK with GO Feature Flag provider
const goFeatureFlagProvider = new GoFeatureFlagProvider({
  endpoint: 'http://localhost:1031/' // DNS of your instance of relay proxy
});
OpenFeature.setProvider(goFeatureFlagProvider);
const featureFlagClient = OpenFeature.getClient('my-app')
Evaluate your flag

Now you can evaluate your flags anywhere in your code using this client.

// Context of your flag evaluation.
// With GO Feature Flag you MUST provide a targetingKey that is a unique identifier of the user.
const evaluationContext = {
  targetingKey: '1d1b9238-2591-4a47-94cf-d2bc080892f1', // user unique identifier (mandatory)
  firstname: 'john',
  lastname: 'doe',
  email: 'john.doe@gofeatureflag.org',
  admin: true, // this field is used in the targeting rule of the flag "flag-only-for-admin"
  // ...
};

const adminFlag = await featureFlagClient.getBooleanValue('flag-only-for-admin', false, evaluationContext);
if (adminFlag) {
  // flag "flag-only-for-admin" is true for the user
  console.log("new feature");
} else {
  // flag "flag-only-for-admin" is false for the user
}

Using the GO Module
Installation
go get github.com/thomaspoignant/go-feature-flag
Create a feature flag configuration

Create a new YAML file containing your first flag configuration.

# 20% of the users will use the variation "my-new-feature"
test-flag:
  variations:
    my-new-feature: true
    my-old-feature: false
  defaultRule:
    percentage:
      my-new-feature: 20
      my-old-feature: 80

This flag split the usage of this flag, 20% will use the variation my-new-feature and 80% the variation my-old-feature.

SDK Initialisation

First, you need to initialize the ffclient with the location of your backend file.

err := ffclient.Init(ffclient.Config{
  PollingInterval: 3 * time.Second,
  Retriever:      &fileretriever.Retriever{
    Path: "flag-config.goff.yaml",
  },
})
defer ffclient.Close()

This example will load a file from your local computer and will refresh the flags every 3 seconds (if you omit the PollingInterval, the default value is 60 seconds).

ℹ info
This is a basic configuration to test locally, in production it is better to use a remote place to store your feature flag configuration file.
Look at the list of available options in the Store your feature flag file page.

Evaluate your flags

Now you can evaluate your flags anywhere in your code.

user := ffcontext.NewEvaluationContext("user-unique-key")
hasFlag, _ := ffclient.BoolVariation("test-flag", user, false)
if hasFlag {
  // flag "test-flag" is true for the user
} else {
  // flag "test-flag" is false for the user
}

The full documentation is available on https://docs.gofeatureflag.org
You can find more examples in the examples/ directory.

Can I use GO Feature Flag with any language?

Originally GO Feature Flag was built to be a GOlang only library, but it limits the ecosystem too much.
To be compatible with more languages we have implemented the GO Feature Flag Relay Proxy. It is a service you can host that provides an API to evaluate your flags, you can call it using HTTP to get your variation.

Since we believe in standardization we are also implementing OpenFeature providers to interact with this API in the language of your choice.
(OpenFeature is still at an early stage, so not all languages are supported and expect some changes in the future)

For now, we have providers for:

Language Provider Source Version
Go Go Provider version
Java / Kotlin (server) Java Provider version
Android / Kotlin (client) Kotlin Provider version
Javascript/Typescript (server) Server Provider version
Javascript/Typescript (client) Client Provider version
Python Python Provider version
.Net .Net Provider version
Ruby Ruby Provider version
Swift Swift Provider version
PHP PHP Provider version

Where do I store my flags file?

The module supports different ways of retrieving the flag file.
The available retrievers are:

  • GitHub
  • GitLab
  • HTTP endpoint
  • AWS S3
  • Local file
  • Google Cloud Storage
  • Kubernetes ConfigMaps
  • MongoDB
  • Redis
  • BitBucket
  • AzBlobStorage
  • ...

See the full list and more information.

Flags file format

GO Feature Flag core feature is to centralize all your feature flags in a single file and to avoid hosting and maintaining a backend server to manage them.

Your file should be a YAML, JSON or TOML file with a list of flags (examples: YAML, JSON, TOML).

The easiest way to create your configuration file is to use GO Feature Flag Editor available at https://editor.gofeatureflag.org.
If you prefer to do it manually please follow the instruction below.

A flag configuration looks like this:

YAML
# This is your configuration for your first flag
first-flag:
  variations: # All possible return value for your feature flag
    A: false
    B: true
  targeting: # If you want to target a subset of your users in particular
    - query: key eq "random-key"
      percentage:
        A: 0
        B: 100
  defaultRule: # When no targeting match we use the defaultRule
    variation: A

# A second example of a flag configuration
second-flag:
  variations:
    A: "valueA"
    B: "valueB"
    defaultValue: "a default value"
  targeting:
    - name: notkey_rule
      query: key eq "not-a-key"
      percentage:
        A: 10
        B: 90
  defaultRule:
    variation: defaultValue
  version: "12"
  experimentation:
    start: 2021-03-20T00:00:00.1-05:00
    end: 2021-03-21T00:00:00.1-05:00
JSON
{
  "first-flag": {
    "variations": {
      "A": false,
      "B": true
    },
    "targeting": [
      {
        "query": "key eq \"random-key\"",
        "percentage": {
          "A": 0,
          "B": 100
        }
      }
    ],
    "defaultRule": {
      "variation": "A"
    }
  },

  "second-flag": {
    "variations": {
      "A": "valueA",
      "B": "valueB",
      "defaultValue": "a default value"
    },
    "targeting": [
      {
        "name": "notkey_rule",
        "query": "key eq \"not-a-key\"",
        "percentage": {
          "A": 10,
          "B": 90
        }
      }
    ],
    "defaultRule": {
      "variation": "defaultValue"
    },
    "version": "12",
    "experimentation": {
      "start": "2021-03-20T05:00:00.100Z",
      "end": "2021-03-21T05:00:00.100Z"
    }
  }
}
TOML
[first-flag.variations]
A = false
B = true

[[first-flag.targeting]]
query = 'key eq "random-key"'

[first-flag.targeting.percentage]
A = 0
B = 100

[first-flag.defaultRule]
variation = "A"

[second-flag]
version = "12"

[second-flag.variations]
A = "valueA"
B = "valueB"
defaultValue = "a default value"

[[second-flag.targeting]]
name = "notkey_rule"
query = 'key eq "not-a-key"'

[second-flag.targeting.percentage]
A = 10
B = 90

[second-flag.defaultRule]
variation = "defaultValue"

[second-flag.experimentation]
start = 2021-03-20T05:00:00.100Z
end = 2021-03-21T05:00:00.100Z

For detailed information on the fields required to create a flag, please refer to the documentation.

Rule format

The query format is based on the nikunjy/rules library.

All the operations can be written in capitalized or lowercase (ex: eq or EQ can be used).
Logical Operations supported are AND OR.

Compare Expression and their definitions (a|b means you can use either one of the two a or b):

eq|==: equals to 
ne|!=: not equals to
lt|<: less than 
gt|>: greater than
le|<=: less than equal to
ge|>=: greater than equal to 
co: contains 
sw: starts with 
ew: ends with
in: in a list
pr: present
not: not of a logical expression
Examples
  • Select a specific user: key eq "example@example.com"
  • Select all identified users: anonymous ne true
  • Select a user with a custom property: userId eq "12345"

Evaluation Context

An evaluation context in a feature flagging system is crucial for determining the output of a feature flag evaluation. It's a collection of pertinent data about the conditions under which the evaluation is being made. This data can be supplied through a mix of static information (server name, IP, etc ...) and dynamic inputs (information about the user performing the action, etc ...), along with state information that is implicitly carried through the execution of the program.

When using GO Feature Flag, it's often necessary to personalize the experience for different users. This is where the concept of a targeting key comes into play. A targeting key is a unique identifier that represents the context of the evaluation (email, session id, a fingerprint or anything that is consistent), ensuring that they are consistently exposed to the same variation of a feature, even across multiple visits or sessions.

For instance, GO Feature Flag ensures that in cases where a feature is being rolled out to a percentage of users, based on the targeting key, they will see the same variation each time they encounter the feature flag.

The targeting key is a fundamental part of the evaluation context because it directly affects the determination of which feature variant is served to a particular user, and it maintains that continuity over time. To do so GO Feature Flag to do a hash to define if the flag can apply to this evaluation context or not.
We recommend using a hash if possible.

Feature flag targeting and rollouts are all determined by the user you pass to your evaluation calls.

Custom bucketing

In some cases, you might need to bucket users based on a different key, e.g. a teamId, so that users within the same team get exposed to the same flag variation and get a consistent experience.

This can be achieved by defining the bucketingKey field in the flag configuration. When present, the value corresponding to the bucketingKey will be extracted from the attributes, and that value used for hashing and determining the outcome in place of the targetingKey.

Variations

Variations are the different values possible for a feature flag.
GO Feature Flag can manage more than just boolean values; the value of your flag can be any of the following types:

  • bool
  • int
  • float
  • string
  • json array
  • json object
Example
Boolean result = featureFlagClient.getBooleanValue("your.feature.key", false, userContext);

// this example is using the java SDK
// result is now true or false depending on the setting of this boolean feature flag

Variation methods take the feature flag key, an evaluation context, and a default value.

Why do we need a default value? If we have any error during the evaluation of the flag, we will return the default value, you will always get a value return from the function and we will never throw an error.

In the example, if the flag your.feature.key does not exist, the result will be false.
Note that the result will always provide a usable value.

Rollout

A critical part of every new feature release is orchestrating the actual launch schedule between the Product, Engineering, and Marketing teams.

Delivering powerful user experiences typically requires software teams to manage complex releases and make manual updates at inconvenient times.

But it does not have to, having a complex rollout strategy allows you to have a lifecycle for your flags.

Complex rollout strategy available

Notifiers

If you want to be informed when a flag has changed, you can configure a notifier.

A notifier will send one notification to the targeted system to inform them that a new flag configuration has been loaded.

ℹ️ GO Feature Flag can handle more than one notifier at a time.

Available notifiers are:

  • Slack
  • Webhook
  • Discord
  • Microsoft Teams

Export data

GO Feature Flag allows you to export data about the usage of your flags.
It collects all variation events and can save these events in several locations:

  • Local file - create local files with the variation usages.
  • Log - use your logger to write the variation usages.
  • AWS S3 - export your variation usages to S3.
  • AWS Kinesis - publish your variation usages to AWS Kinesis Stream.
  • Google Cloud Storage - export your variation usages to Google Cloud Storage.
  • Webhook - export your variation usages by calling a webhook.
  • AWS SQS - export your variation usages by sending events to SQS.
  • Google PubSub - export your variation usages by publishing events to PubSub topic.

Currently, we are supporting only feature events.
It represents individual flag evaluations and is considered "full fidelity" events.

An example feature event below:

{
  "kind": "feature",
  "contextKind": "anonymousUser",
  "userKey": "ABCD",
  "creationDate": 1618228297,
  "key": "test-flag",
  "variation": "Default",
  "value": false,
  "default": false,
  "source": "SERVER"
}

The format of the data is described in the documentation. Events are collected and sent in bulk to avoid spamming your exporter.

Linter

A command line tool is available to help you lint your configuration file: go-feature-flag-lint.

How can I contribute?

This project welcomes contributions from the community. If you're interested in contributing, see the contributors' guide for some helpful tips.

Community meetings

Since everyone's voice is important we want to hear back from the community.
For this reason, we are launching a community meeting every 2 weeks and it is the perfect place to discuss the future of GO Feature Flag and help you use it at full potential.

Name Meeting Time Meeting Notes Discussions
GO Feature Flag Community Meeting Every other Thursday at 10:00 am ET / 16:00 CET Google Doc VC Link (meet)

Contributors

Thanks so much to our contributors.

Sponsors

Become a sponsor and show your support to GO Feature Flag.

These are our really cool sponsors!

Cybozu

Adopters

If you are using go-feature-flag, we encourage you to include your company's name in this list. This simple act significantly boosts the project's visibility and credibility, making a substantial contribution to its advancement. To do so, kindly add yourself to adopters.

Here is the list of adopters.

Documentation

Overview

Package ffclient aids adding instrumentation to have feature flags in your app without any backend server.

Summary

This package and its subpackages contain bits of code to have an easy feature flag solution with no complex installation to do on your infrastructure and without using 3rd party vendor for this.

The ffclient package provides the entry point - initialization and the basic method to get your flags value.

Before using the module you need to initialize it this way:

 import (
	  ffclient "github.com/thomaspoignant/go-feature-flag"
	  "github.com/thomaspoignant/go-feature-flag/retriever/httpretriever"
	  ...
 )

 func main() {
	  err := ffclient.Init(ffclient.Config{
	      PollingInterval: 3 * time.Second,
	      Retriever: &httpretriever.Retriever{
	          URL:  "https://code.gofeatureflag.org/blob/main/testdata/flag-config.yaml",
	      },
	  })
	  defer ffclient.Close()
	  ...

This example will load a file from an HTTP endpoint and will refresh the flags every 3 seconds.

Now you can evaluate your flags anywhere in your code.

		  ...
		  evaluationContext := ffcontext.NewEvaluationContext("user-unique-key")
		  hasFlag, _ := ffclient.BoolVariation("test-flag", evaluationContext, false)
		  if hasFlag {
		      //flag "test-flag" is true for the user
		  } else {
		     // flag "test-flag" is false for the user
		  }
		  ...
  }

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllFlagsState added in v0.17.0

func AllFlagsState(ctx ffcontext.Context) flagstate.AllFlags

AllFlagsState return the values of all the flags for a specific user. If a valid field is false, it means that we had an error when checking the flags.

func BoolVariation

func BoolVariation(flagKey string, ctx ffcontext.Context, defaultValue bool) (bool, error)

BoolVariation return the value of the flag in boolean. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func BoolVariationDetails added in v1.1.0

func BoolVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue bool) (
	model.VariationResult[bool], error)

BoolVariationDetails return the details of the evaluation for boolean flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func Close

func Close()

Close the component by stopping the background refresh and clean the cache.

func Float64Variation

func Float64Variation(flagKey string, ctx ffcontext.Context, defaultValue float64) (float64, error)

Float64Variation return the value of the flag in float64. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func Float64VariationDetails added in v1.1.0

func Float64VariationDetails(flagKey string, ctx ffcontext.Context, defaultValue float64,
) (model.VariationResult[float64], error)

Float64VariationDetails return the details of the evaluation for float64 flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func ForceRefresh added in v1.28.0

func ForceRefresh() bool

ForceRefresh is a function that forces to call the retrievers and refresh the configuration of flags. This function can be called explicitly to refresh the flags if you know that a change has been made in the configuration.

func GetCacheRefreshDate added in v0.22.0

func GetCacheRefreshDate() time.Time

GetCacheRefreshDate gives the last refresh date of the cache

func GetFlagsFromCache added in v0.24.0

func GetFlagsFromCache() (map[string]flag.Flag, error)

GetFlagsFromCache returns all the flags present in the cache with their current state when calling this method. If cache hasn't been initialized, an error reporting this is returned.

func Init

func Init(config Config) error

Init the feature flag component with the configuration of ffclient.Config

func main() {
  err := ffclient.Init(ffclient.Config{
           PollingInterval: 3 * time.Second,
           Retriever: &httpretriever.Retriever{
             URL:    "http://example.com/flag-config.yaml",
           },
         })
  defer ffclient.Close()

func IntVariation

func IntVariation(flagKey string, ctx ffcontext.Context, defaultValue int) (int, error)

IntVariation return the value of the flag in int. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func IntVariationDetails added in v1.1.0

func IntVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue int) (model.VariationResult[int], error)

IntVariationDetails return the details of the evaluation for int flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func IsOffline added in v1.27.0

func IsOffline() bool

IsOffline allows knowing if the feature flag is in offline mode

func JSONArrayVariation

func JSONArrayVariation(flagKey string, ctx ffcontext.Context, defaultValue []interface{}) ([]interface{}, error)

JSONArrayVariation return the value of the flag in []interface{}. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func JSONArrayVariationDetails added in v1.1.0

func JSONArrayVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue []interface{},
) (model.VariationResult[[]interface{}], error)

JSONArrayVariationDetails return the details of the evaluation for []interface{} flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func JSONVariation

func JSONVariation(
	flagKey string, ctx ffcontext.Context, defaultValue map[string]interface{},
) (map[string]interface{}, error)

JSONVariation return the value of the flag in map[string]interface{}. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func JSONVariationDetails added in v1.1.0

func JSONVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue map[string]interface{},
) (model.VariationResult[map[string]interface{}], error)

JSONVariationDetails return the details of the evaluation for map[string]interface{} flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func SetOffline added in v1.27.0

func SetOffline(control bool)

SetOffline updates the config Offline parameter

func StringVariation

func StringVariation(flagKey string, ctx ffcontext.Context, defaultValue string) (string, error)

StringVariation return the value of the flag in string. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

func StringVariationDetails added in v1.1.0

func StringVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue string,
) (model.VariationResult[string], error)

StringVariationDetails return the details of the evaluation for string flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value.

Types

type Config

type Config struct {
	// PollingInterval (optional) Poll every X time
	// The minimum possible is 1 second
	// Default: 60 seconds
	PollingInterval time.Duration

	// EnablePollingJitter (optional) set to true if you want to avoid having true periodicity when
	// retrieving your flags. It is useful to avoid having spike on your flag configuration storage
	// in case your application is starting multiple instance at the same time.
	// We ensure a deviation that is maximum + or - 10% of your polling interval.
	// Default: false
	EnablePollingJitter bool

	// DisableNotifierOnInit (optional) set to true if you do not want to call any notifier
	// when the flags are loaded.
	// This is useful if you do not want a Slack/Webhook notification saying that
	// the flags have been added every time you start the application.
	// Default is set to false for backward compatibility.
	// Default: false
	DisableNotifierOnInit bool

	// Deprecated: Use LeveledLogger instead
	// Logger (optional) logger use by the library
	// Default: No log
	Logger *log.Logger

	// LeveledLogger (optional) logger use by the library
	// Default: No log
	LeveledLogger *slog.Logger

	// Context (optional) used to call other services (HTTP, S3 ...)
	// Default: context.Background()
	Context context.Context

	// Environment (optional) can be checked in feature flag rules
	// Default: ""
	Environment string

	// Retriever is the component in charge to retrieve your flag file
	Retriever retriever.Retriever

	// Retrievers is the list of components in charge to retrieving your flag files.
	// We are dealing with config files in order, if you have the same flag name in multiple files it will be override
	// based of the order of the retrievers in the slice.
	//
	// Note: If both Retriever and Retrievers are set, we will start by calling the Retriever and,
	// after we will use the order of Retrievers.
	Retrievers []retriever.Retriever

	// Notifiers (optional) is the list of notifiers called when a flag change
	Notifiers []notifier.Notifier

	// FileFormat (optional) is the format of the file to retrieve (available YAML, TOML and JSON)
	// Default: YAML
	FileFormat string

	// DataExporter (optional) is the configuration where we store how we should output the flags variations results
	DataExporter DataExporter

	// StartWithRetrieverError (optional) If true, the SDK will start even if we did not get any flags from the retriever.
	// It will serve only default values until all the retrievers returns the flags.
	// The init method will not return any error if the flag file is unreachable.
	// Default: false
	StartWithRetrieverError bool

	// Offline (optional) If true, the SDK will not try to retrieve the flag file and will not export any data.
	// No notification will be sent neither.
	// Default: false
	Offline bool

	// EvaluationContextEnrichment (optional) will be merged with the evaluation context sent during the evaluation.
	// It is useful to add common attributes to all the evaluation, such as a server version, environment, ...
	//
	// All those fields will be included in the custom attributes of the evaluation context,
	// if in the evaluation context you have a field with the same name, it will override the common one.
	// Default: nil
	EvaluationContextEnrichment map[string]interface{}

	// PersistentFlagConfigurationFile (optional) if set GO Feature Flag will store flags configuration in this file
	//  to be able to serve the flags even if none of the retrievers is available during starting time.
	//
	// By default, the flag configuration is not persisted and stays on the retriever system. By setting a file here,
	// you ensure that GO Feature Flag will always start with a configuration but which can be out-dated.
	PersistentFlagConfigurationFile string
	// contains filtered or unexported fields
}

Config is the configuration of go-feature-flag. You should also have a retriever to specify where to read the flags file.

func (*Config) GetRetrievers added in v1.5.0

func (c *Config) GetRetrievers() ([]retriever.Retriever, error)

GetRetrievers returns a retriever.Retriever configure with the retriever available in the config.

func (*Config) IsOffline added in v1.27.0

func (c *Config) IsOffline() bool

IsOffline return if the GO Feature Flag is in offline mode.

func (*Config) SetOffline added in v1.27.0

func (c *Config) SetOffline(control bool)

SetOffline set GO Feature Flag in offline mode.

type DataExporter added in v0.10.0

type DataExporter struct {
	// FlushInterval is the interval we are waiting to export the data.
	// example: if you set your FlushInterval to 1 minutes, we will send
	// the data every minute unless we reach the max event in cache before.
	FlushInterval time.Duration

	// MaxEventInMemory is the maximum number of event you keep in the cache
	// before sending the data to the Exporter.
	// We will send the data when the MaxEventInMemory is reach or if we have
	// waited the FlushInterval.
	MaxEventInMemory int64

	// Exporter is the configuration of your exporter.
	// You can see all available exporter in the exporter package.
	Exporter exporter.CommonExporter
}

DataExporter is the configuration of your export target.

type GoFeatureFlag added in v0.6.0

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

GoFeatureFlag is the main object of the library it contains the cache, the config, the updater and the exporter.

func New added in v0.6.0

func New(config Config) (*GoFeatureFlag, error)

New creates a new go-feature-flag instances that retrieve the config from a YAML file and return everything you need to manage your flags.

func (*GoFeatureFlag) AllFlagsState added in v0.17.0

func (g *GoFeatureFlag) AllFlagsState(evaluationCtx ffcontext.Context) flagstate.AllFlags

AllFlagsState return a flagstate.AllFlags that contains all the flags for a specific user.

func (*GoFeatureFlag) BoolVariation added in v0.6.0

func (g *GoFeatureFlag) BoolVariation(flagKey string, ctx ffcontext.Context, defaultValue bool) (bool, error)

BoolVariation return the value of the flag in boolean. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) BoolVariationDetails added in v1.1.0

func (g *GoFeatureFlag) BoolVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue bool,
) (model.VariationResult[bool], error)

BoolVariationDetails return the details of the evaluation for boolean flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) Close added in v0.6.0

func (g *GoFeatureFlag) Close()

Close wait until thread are done

func (*GoFeatureFlag) CollectEventData added in v1.7.0

func (g *GoFeatureFlag) CollectEventData(event exporter.FeatureEvent)

CollectEventData is collecting events and sending them to the data exporter to be stored.

func (*GoFeatureFlag) Float64Variation added in v0.6.0

func (g *GoFeatureFlag) Float64Variation(flagKey string, ctx ffcontext.Context, defaultValue float64) (float64, error)

Float64Variation return the value of the flag in float64. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) Float64VariationDetails added in v1.1.0

func (g *GoFeatureFlag) Float64VariationDetails(flagKey string, ctx ffcontext.Context, defaultValue float64,
) (model.VariationResult[float64], error)

Float64VariationDetails return the details of the evaluation for float64 flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) ForceRefresh added in v1.28.0

func (g *GoFeatureFlag) ForceRefresh() bool

ForceRefresh is a function that forces to call the retrievers and refresh the configuration of flags. This function can be called explicitly to refresh the flags if you know that a change has been made in the configuration.

func (*GoFeatureFlag) GetCacheRefreshDate added in v0.22.0

func (g *GoFeatureFlag) GetCacheRefreshDate() time.Time

GetCacheRefreshDate gives the last refresh date of the cache

func (*GoFeatureFlag) GetFlagStates added in v1.33.0

func (g *GoFeatureFlag) GetFlagStates(evaluationCtx ffcontext.Context, flagsToEvaluate []string) flagstate.AllFlags

GetFlagStates is evaluating all the flags in flagsToEvaluate based on the context provided. If flagsToEvaluate is nil or empty, it will evaluate all the flags available in GO Feature Flag.

func (*GoFeatureFlag) GetFlagsFromCache added in v0.24.0

func (g *GoFeatureFlag) GetFlagsFromCache() (map[string]flag.Flag, error)

GetFlagsFromCache returns all the flags present in the cache with their current state when calling this method. If cache hasn't been initialized, an error reporting this is returned.

func (*GoFeatureFlag) GetPollingInterval added in v1.27.0

func (g *GoFeatureFlag) GetPollingInterval() int64

GetPollingInterval is the polling interval between two refreshes of the cache

func (*GoFeatureFlag) IntVariation added in v0.6.0

func (g *GoFeatureFlag) IntVariation(flagKey string, ctx ffcontext.Context, defaultValue int) (int, error)

IntVariation return the value of the flag in int. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) IntVariationDetails added in v1.1.0

func (g *GoFeatureFlag) IntVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue int,
) (model.VariationResult[int], error)

IntVariationDetails return the details of the evaluation for int flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) IsOffline added in v1.27.0

func (g *GoFeatureFlag) IsOffline() bool

IsOffline allows knowing if the feature flag is in offline mode

func (*GoFeatureFlag) JSONArrayVariation added in v0.6.0

func (g *GoFeatureFlag) JSONArrayVariation(
	flagKey string, ctx ffcontext.Context, defaultValue []interface{},
) ([]interface{}, error)

JSONArrayVariation return the value of the flag in []interface{}. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) JSONArrayVariationDetails added in v1.1.0

func (g *GoFeatureFlag) JSONArrayVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue []interface{},
) (model.VariationResult[[]interface{}], error)

JSONArrayVariationDetails return the details of the evaluation for []interface{} flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) JSONVariation added in v0.6.0

func (g *GoFeatureFlag) JSONVariation(
	flagKey string, ctx ffcontext.Context, defaultValue map[string]interface{},
) (map[string]interface{}, error)

JSONVariation return the value of the flag in map[string]interface{}. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) JSONVariationDetails added in v1.1.0

func (g *GoFeatureFlag) JSONVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue map[string]interface{},
) (model.VariationResult[map[string]interface{}], error)

JSONVariationDetails return the details of the evaluation for []interface{} flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) RawVariation added in v0.22.2

func (g *GoFeatureFlag) RawVariation(flagKey string, ctx ffcontext.Context, sdkDefaultValue interface{},
) (model.RawVarResult, error)

RawVariation return the raw value of the flag (without any types). This raw result is mostly used by software built on top of go-feature-flag such as go-feature-flag relay proxy. If you are using directly the library you should avoid calling this function. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) SetOffline added in v1.27.0

func (g *GoFeatureFlag) SetOffline(control bool)

SetOffline updates the config Offline parameter

func (*GoFeatureFlag) StringVariation added in v0.6.0

func (g *GoFeatureFlag) StringVariation(flagKey string, ctx ffcontext.Context, defaultValue string) (string, error)

StringVariation return the value of the flag in string. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

func (*GoFeatureFlag) StringVariationDetails added in v1.1.0

func (g *GoFeatureFlag) StringVariationDetails(flagKey string, ctx ffcontext.Context, defaultValue string,
) (model.VariationResult[string], error)

StringVariationDetails return the details of the evaluation for string flag. An error is return if you don't have init the library before calling the function. If the key does not exist we return the default value. Note: Use this function only if you are using multiple go-feature-flag instances.

Directories

Path Synopsis
cmd
cli
relayproxy/docs
Package docs Code generated by swaggo/swag.
Package docs Code generated by swaggo/swag.
relayproxy/modeldocs
nolint: lll
nolint: lll
examples
Package exporter defines the data exporter of go-feature-flag
Package exporter defines the data exporter of go-feature-flag
Package ffuser defines the go-feature-flag model for user properties.
Package ffuser defines the go-feature-flag model for user properties.
dto
Package testutils is a generated GoMock package.
Package testutils is a generated GoMock package.
utils

Jump to

Keyboard shortcuts

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