OpenFeature Go SDK
Quick start
Requirements
Go language version: 1.20
Note
The OpenFeature Go SDK only supports currently maintained Go language versions.
Install
go get github.com/open-feature/go-sdk
Usage
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.
API Reference
See here for the complete API documentation.
Features
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. |
Providers
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.
Targeting
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
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{}),
)
Logging
The standard Go log package is used by default to show error logs. This can be overridden using the structured logging, logr API, allowing integration to any package. There are already integration implementations for many of the popular logger packages.
var l logr.Logger
l = integratedlogr.New() // replace with your chosen integrator
openfeature.SetLogger(l) // set the logger at global level
c := openfeature.NewClient("log").WithLogger(l) // set the logger at client level
logr uses incremental verbosity levels (akin to named levels but in integer form).
The SDK logs info
at level 0
and debug
at level 1
. Errors are always logged.
Domains
Clients can be assigned to a domain. A domain is a logical identifier which 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")
Eventing
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)
Shutdown
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 Propagation
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, ....)
Extending
Develop a provider
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!
Develop a hook
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!
Testing
To test interactions with OpenFeature API and Client, you can rely on openfeature.IEvaluation
& openfeature.IClient
interfaces.
While you may use global methods to interact with the API, it is recommended to obtain the singleton API instance so that you can use appropriate mocks for your testing needs,
// global helper
openfeature.SetProvider(myProvider)
// singleton instance - preferred
apiInstance := openfeature.GetApiInstance()
apiInstance.SetProvider(myProvider)
Similarly, while you have option (due to historical reasons) to create a client with openfeature.NewClient()
helper, it is recommended to use API to generate the client which returns an IClient
instance.
// global helper
openfeature.NewClient("myClient")
// using API instance - preferred
apiInstance := openfeature.GetApiInstance()
apiInstance.GetClient()
apiInstance.GetNamedClient("myClient")