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. |
β | Named clients | Utilize multiple providers in a single application. |
β | Eventing | React to state changes in the provider or flag management system. |
β | Shutdown | Gracefully clean up a provider during application shutdown. |
β | 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 named clients, 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 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.
Clients can be given a name. A name is a logical identifier which can be used to associate clients with a particular provider. If a name has no associated provider, the global 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()
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!
- 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.