OpenFeature is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool.
Go language version: 1.20
Note
The OpenFeature Go SDK only supports currently maintained Go language versions.
go get github.com/open-feature/go-sdk
package main
import (
"fmt"
"context"
"github.com/open-feature/go-sdk/openfeature"
)
func main() {
// Register your feature flag provider
openfeature.SetProvider(openfeature.NoopProvider{})
// Create a new client
client := openfeature.NewClient("app")
// Evaluate your feature flag
v2Enabled, _ := client.BooleanValue(
context.Background(), "v2_enabled", true, openfeature.EvaluationContext{},
)
// Use the returned flag value
if v2Enabled {
fmt.Println("v2 is enabled")
}
}
Try this example in the Go Playground.
See here for the complete API documentation.
Status | Features | Description |
---|---|---|
✅ | Providers | Integrate with a commercial, open source, or in-house feature management tool. |
✅ | Targeting | Contextually-aware flag evaluation using evaluation context. |
✅ | Hooks | Add functionality to various stages of the flag evaluation life-cycle. |
✅ | Logging | Integrate with popular logging packages. |
✅ | Domains | Logically bind clients with providers. |
✅ | Eventing | React to state changes in the provider or flag management system. |
✅ | Shutdown | Gracefully clean up a provider during application shutdown. |
✅ | Transaction Context Propagation | Set a specific evaluation context for a transaction (e.g. an HTTP request or a thread) |
✅ | Extending | Extend OpenFeature with custom providers and hooks. |
Implemented: ✅ | In-progress:
Providers are an abstraction between a flag management system and the OpenFeature SDK. Look here for a complete list of available providers. If the provider you're looking for hasn't been created yet, see the develop a provider section to learn how to build it yourself.
Once you've added a provider as a dependency, it can be registered with OpenFeature like this:
openfeature.SetProvider(MyProvider{})
In some situations, it may be beneficial to register multiple providers in the same application. This is possible using domains, which is covered in more details below.
Sometimes, the value of a flag must consider some dynamic criteria about the application or user, such as the user's location, IP, email address, or the server's location. In OpenFeature, we refer to this as targeting. If the flag management system you're using supports targeting, you can provide the input data using the evaluation context.
// set a value to the global context
openfeature.SetEvaluationContext(openfeature.NewTargetlessEvaluationContext(
map[string]interface{}{
"region": "us-east-1-iah-1a",
},
))
// set a value to the client context
client := openfeature.NewClient("my-app")
client.SetEvaluationContext(openfeature.NewTargetlessEvaluationContext(
map[string]interface{}{
"version": "1.4.6",
},
))
// set a value to the invocation context
evalCtx := openfeature.NewEvaluationContext(
"user-123",
map[string]interface{}{
"company": "Initech",
},
)
boolValue, err := client.BooleanValue("boolFlag", false, evalCtx)
Hooks allow for custom logic to be added at well-defined points of the flag evaluation life-cycle Look here for a complete list of available hooks. If the hook you're looking for hasn't been created yet, see the develop a hook section to learn how to build it yourself.
Once you've added a hook as a dependency, it can be registered at the global, client, or flag invocation level.
// add a hook globally, to run on all evaluations
openfeature.AddHooks(ExampleGlobalHook{})
// add a hook on this client, to run on all evaluations made by this client
client := openfeature.NewClient("my-app")
client.AddHooks(ExampleClientHook{})
// add a hook for this evaluation only
value, err := client.BooleanValue(
context.Background(), "boolFlag", false, openfeature.EvaluationContext{}, WithHooks(ExampleInvocationHook{}),
)
The tracking API allows you to use OpenFeature abstractions and objects to associate user actions with feature flag evaluations.
This is essential for robust experimentation powered by feature flags.
For example, a flag enhancing the appearance of a UI component might drive user engagement to a new feature; to test this hypothesis, telemetry collected by a hook or provider can be associated with telemetry reported in the client's track
function.
// initilize a client
client := openfeature.NewClient('my-app')
// trigger tracking event action
client.Track(
context.Background(),
'visited-promo-page',
openfeature.EvaluationContext{},
openfeature.NewTrackingEventDetails(99.77).Add("currencyCode", "USD"),
)
Note that some providers may not support tracking; check the documentation for your provider for more information.
Note that in accordance with the OpenFeature specification, the SDK doesn't generally log messages during flag evaluation.
The GO SDK includes a LoggingHook
, which logs detailed information at key points during flag evaluation, using slog structured logging API.
This hook can be particularly helpful for troubleshooting and debugging; simply attach it at the global, client or invocation level and ensure your log level is set to "debug".
// configure slog
var programLevel = new(slog.LevelVar)
programLevel.Set(slog.LevelDebug)
h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel})
slog.SetDefault(slog.New(h))
// add a hook globally to run on all evaluations
hook, err := NewLoggingHook(false)
if err != nil {
// handle error
}
openfeature.AddHooks(hook)
client.BooleanValueDetails(context.Background(), "not-exist", true, openfeature.EvaluationContext{})
{"time":"2024-10-23T13:33:09.8870867+03:00","level":"DEBUG","msg":"Before stage","domain":"test-client","provider_name":"InMemoryProvider","flag_key":"not-exist","default_value":true}
{"time":"2024-10-23T13:33:09.8968242+03:00","level":"ERROR","msg":"Error stage","domain":"test-client","provider_name":"InMemoryProvider","flag_key":"not-exist","default_value":true,"error_message":"error code: FLAG_NOT_FOUND: flag for key not-exist not found"}
See hooks for more information on configuring hooks.
Clients can be assigned to a domain. A domain is a logical identifier that can be used to associate clients with a particular provider. If a domain has no associated provider, the default provider is used.
import "github.com/open-feature/go-sdk/openfeature"
// Registering the default provider
openfeature.SetProvider(NewLocalProvider())
// Registering a named provider
openfeature.SetNamedProvider("clientForCache", NewCachedProvider())
// A Client backed by default provider
clientWithDefault := openfeature.NewClient("")
// A Client backed by NewCachedProvider
clientForCache := openfeature.NewClient("clientForCache")
Events allow you to react to state changes in the provider or underlying flag management system, such as flag definition changes, provider readiness, or error conditions.
Initialization events (PROVIDER_READY
on success, PROVIDER_ERROR
on failure) are dispatched for every provider.
Some providers support additional events, such as PROVIDER_CONFIGURATION_CHANGED
.
Please refer to the documentation of the provider you're using to see what events are supported.
import "github.com/open-feature/go-sdk/openfeature"
...
var readyHandlerCallback = func(details openfeature.EventDetails) {
// callback implementation
}
// Global event handler
openfeature.AddHandler(openfeature.ProviderReady, &readyHandlerCallback)
...
var providerErrorCallback = func(details openfeature.EventDetails) {
// callback implementation
}
client := openfeature.NewClient("clientName")
// Client event handler
client.AddHandler(openfeature.ProviderError, &providerErrorCallback)
The OpenFeature API provides a close function to perform a cleanup of all registered providers. This should only be called when your application is in the process of shutting down.
import "github.com/open-feature/go-sdk/openfeature"
openfeature.Shutdown()
Transaction context is a container for transaction-specific evaluation context (e.g. user id, user agent, IP). Transaction context can be set where specific data is available (e.g. an auth service or request handler), and by using the transaction context propagator, it will automatically be applied to all flag evaluations within a transaction (e.g. a request or thread).
import "github.com/open-feature/go-sdk/openfeature"
// set the TransactionContext
ctx := openfeature.WithTransactionContext(context.Background(), openfeature.EvaluationContext{})
// get the TransactionContext from a context
ec := openfeature.TransactionContext(ctx)
// merge an EvaluationContext with the existing TransactionContext, preferring
// the context that is passed to MergeTransactionContext
tCtx := openfeature.MergeTransactionContext(ctx, openfeature.EvaluationContext{})
// use TransactionContext in a flag evaluation
client.BooleanValue(tCtx, ....)
To develop a provider, you need to create a new project and include the OpenFeature SDK as a dependency.
This can be a new repository or included in the existing contrib repository available under the OpenFeature organization.
You’ll then need to write the provider by implementing the FeatureProvider
interface exported by the OpenFeature SDK.
package myfeatureprovider
import (
"context"
"github.com/open-feature/go-sdk/openfeature"
)
// MyFeatureProvider implements the FeatureProvider interface and provides functions for evaluating flags
type MyFeatureProvider struct{}
// Required: Methods below implements openfeature.FeatureProvider interface
// This is the core interface implementation required from a provider
// Metadata returns the metadata of the provider
func (i MyFeatureProvider) Metadata() openfeature.Metadata {
return openfeature.Metadata{
Name: "MyFeatureProvider",
}
}
// Hooks returns a collection of openfeature.Hook defined by this provider
func (i MyFeatureProvider) Hooks() []openfeature.Hook {
// Hooks that should be included with the provider
return []openfeature.Hook{}
}
// BooleanEvaluation returns a boolean flag
func (i MyFeatureProvider) BooleanEvaluation(ctx context.Context, flag string, defaultValue bool, evalCtx openfeature.FlattenedContext) openfeature.BoolResolutionDetail {
// code to evaluate boolean
}
// StringEvaluation returns a string flag
func (i MyFeatureProvider) StringEvaluation(ctx context.Context, flag string, defaultValue string, evalCtx openfeature.FlattenedContext) openfeature.StringResolutionDetail {
// code to evaluate string
}
// FloatEvaluation returns a float flag
func (i MyFeatureProvider) FloatEvaluation(ctx context.Context, flag string, defaultValue float64, evalCtx openfeature.FlattenedContext) openfeature.FloatResolutionDetail {
// code to evaluate float
}
// IntEvaluation returns an int flag
func (i MyFeatureProvider) IntEvaluation(ctx context.Context, flag string, defaultValue int64, evalCtx openfeature.FlattenedContext) openfeature.IntResolutionDetail {
// code to evaluate int
}
// ObjectEvaluation returns an object flag
func (i MyFeatureProvider) ObjectEvaluation(ctx context.Context, flag string, defaultValue interface{}, evalCtx openfeature.FlattenedContext) openfeature.InterfaceResolutionDetail {
// code to evaluate object
}
// Optional: openfeature.StateHandler implementation
// Providers can opt-in for initialization & shutdown behavior by implementing this interface
// Init holds initialization logic of the provider
func (i MyFeatureProvider) Init(evaluationContext openfeature.EvaluationContext) error {
// code to initialize your provider
}
// Status expose the status of the provider
func (i MyFeatureProvider) Status() openfeature.State {
// The state is typically set during initialization.
return openfeature.ReadyState
}
// Shutdown define the shutdown operation of the provider
func (i MyFeatureProvider) Shutdown() {
// code to shutdown your provider
}
// Optional: openfeature.EventHandler implementation.
// Providers can opt-in for eventing support by implementing this interface
// EventChannel returns the event channel of this provider
func (i MyFeatureProvider) EventChannel() <-chan openfeature.Event {
// expose event channel from this provider. SDK listen to this channel and invoke event handlers
}
Built a new provider? Let us know so we can add it to the docs!
To develop a hook, you need to create a new project and include the OpenFeature SDK as a dependency.
This can be a new repository or included in the existing contrib repository available under the OpenFeature organization.
Implement your own hook by conforming to the Hook interface.
To satisfy the interface, all methods (Before
/After
/Finally
/Error
) need to be defined.
To avoid defining empty functions make use of the UnimplementedHook
struct (which already implements all the empty functions).
import (
"context"
"github.com/open-feature/go-sdk/openfeature"
)
type MyHook struct {
openfeature.UnimplementedHook
}
// overrides UnimplementedHook's Error function
func (h MyHook) Error(context context.Context, hookContext openfeature.HookContext, err error, hookHints openfeature.HookHints) {
// code that runs when there's an error during a flag evaluation
}
Built a new hook? Let us know so we can add it to the docs!
The SDK provides a NewTestProvider
which allows you to set flags for the scope of a test.
The TestProvider
is thread-safe and can be used in tests that run in parallel.
Call testProvider.UsingFlags(t, tt.flags)
to set flags for a test, and clean them up with testProvider.Cleanup()
import (
"github.com/open-feature/go-sdk/openfeature"
"github.com/open-feature/go-sdk/openfeature/testing"
)
testProvider := NewTestProvider()
err := openfeature.GetApiInstance().SetProvider(testProvider)
if err != nil {
t.Errorf("unable to set provider")
}
// configure flags for this test suite
tests := map[string]struct {
flags map[string]memprovider.InMemoryFlag
want bool
}{
"test when flag is true": {
flags: map[string]memprovider.InMemoryFlag{
"my_flag": {
State: memprovider.Enabled,
DefaultVariant: "on",
Variants: map[string]any{
"on": true,
},
},
},
want: true,
},
"test when flag is false": {
flags: map[string]memprovider.InMemoryFlag{
"my_flag": {
State: memprovider.Enabled,
DefaultVariant: "off",
Variants: map[string]any{
"off": false,
},
},
},
want: false,
},
}
for name, tt := range tests {
tt := tt
name := name
t.Run(name, func(t *testing.T) {
// be sure to clean up your flags
defer testProvider.Cleanup()
testProvider.UsingFlags(t, tt.flags)
// your code under test
got := functionUnderTest()
if got != tt.want {
t.Fatalf("uh oh, value is not as expected: got %v, want %v", got, tt.want)
}
})
}
- Give this repo a ⭐️!
- Follow us on social media:
- Twitter: @openfeature
- LinkedIn: OpenFeature
- Join us on Slack
- For more, check out our community page
Interested in contributing? Great, we'd love your help! To get started, take a look at the CONTRIBUTING guide.
Made with contrib.rocks.