OpenFeature Go Provider
Introduction
The OpenFeature Go Provider is intended to be used in combination with the OpenFeature Go SDK. The provider wraps the ConfigDirector Go SDK.
The minimum Go version supported is 1.26.
The provider is safe to share between goroutines. Register one instance per process when your application starts, and shut OpenFeature down when it stops. Evaluations read config state the provider already holds in memory, so they make no network calls on the request path.
Installation
The provider can be installed with go get. Its package reference is on pkg.go.dev: https://pkg.go.dev/github.com/ConfigDirector/go-sdks/configdirector-openfeature
The OpenFeature Go SDK (github.com/open-feature/go-sdk) and the ConfigDirector Go SDK are included as dependencies.
go get github.com/ConfigDirector/go-sdks/configdirector-openfeature@latest
Configure and initialize the client
- Create an instance of the provider using your server SDK key. You can retrieve a server SDK key for each environment under
SDK keysin the dashboard's navigation panel. The provider starts connecting as soon as it is created. - Set the OpenFeature provider.
- Get a client instance from OpenFeature.
import (
"log"
"log/slog"
"github.com/ConfigDirector/go-sdks/configdirector"
configdirectoropenfeature "github.com/ConfigDirector/go-sdks/configdirector-openfeature"
"github.com/open-feature/go-sdk/openfeature"
)
// IMPORTANT: Do not commit the server SDK key to your source code, it is a secret value.
provider, err := configdirectoropenfeature.NewProvider(configdirector.Options{SDKKey: "YOUR-SERVER-SDK-KEY"})
if err != nil {
log.Fatal(err)
}
if err := openfeature.SetProviderAndWait(provider); err != nil {
slog.Warn("Starting on in-code default values until ConfigDirector sends config", slog.Any("cause", err))
}
defer openfeature.Shutdown()
client := openfeature.NewClient("my-app")
When no config arrives in time
SetProviderAndWait returns an error when no config arrives from ConfigDirector within the connection timeout, which is 3 seconds unless you set the connection's Timeout, or when ConfigDirector rejects the server SDK key. The error wraps a *openfeature.ProviderInitError with the PROVIDER_NOT_READY error code. The provider then reports ErrorState, with a PROVIDER_ERROR event, and after a timeout it keeps connecting in the background. Until config arrives, flags resolve to their in-code default values with the PROVIDER_NOT_READY error code. Once it arrives, the provider reports ReadyState, with one PROVIDER_READY event. SetProviderWithContextAndWait takes a context that abandons the wait when it ends, and then returns the context's error.
The example above logs the error and starts on in-code default values. To start without waiting for ConfigDirector at all, set the provider with SetProvider instead:
if err := openfeature.SetProvider(provider); err != nil {
log.Fatal(err)
}
Before version 0.4.0 of the provider, SetProviderAndWait returned nil after the timeout, and the provider reported ReadyState while it served in-code default values.
Additional configuration options
The provider takes the same configdirector.Options as the Go SDK client, so every option of the SDK is available on the provider.
For example, the Metadata can be provided like this:
provider, err := configdirectoropenfeature.NewProvider(configdirector.Options{
SDKKey: "YOUR-SERVER-SDK-KEY",
Metadata: configdirector.Metadata{AppName: "YOUR-APP-NAME", AppVersion: "1.0.2"},
})
The provider accepts the same Metadata, Logger, Connection, Telemetry and Hooks options as the Go SDK client, refer to the additional configuration options section of the Go SDK for a full list. Handlers in Hooks run after the provider's own.
That includes running without a connection: created with the connection Mode set to ConnectionModeOffline and no server SDK key, the provider serves the values you give it without connecting to ConfigDirector, SetProviderAndWait returns at once with the provider ready, and NewProvider returns an error when those values cannot be loaded.
Shut down
Shutting OpenFeature down closes the provider, which closes its connections and reports any pending telemetry:
defer openfeature.Shutdown()
Retrieve config values
To retrieve config values, use the OpenFeature client:
Every getter takes a context.Context first, such as the request's context in an HTTP handler, and the evaluation context last:
booleanValue := client.Boolean(ctx, "my-config-key", false, openfeature.EvaluationContext{})
stringValue := client.String(ctx, "my-string-config-key", "Default", openfeature.EvaluationContext{})
Each OpenFeature getter maps to a ConfigDirector config type:
| OpenFeature getter | ConfigDirector config value |
|---|---|
Boolean | Boolean |
String | String or enum |
Int, Float | Number |
Object | JSON object or JSON array |
Object returns the JSON document decoded the way encoding/json decodes into an any: a JSON object is a map[string]any, a JSON array a []any, and a number a float64:
settings := client.Object(ctx, "my-json-config-key", map[string]any{}, openfeature.EvaluationContext{})
theme := settings.(map[string]any)["theme"]
For additional information regarding the OpenFeature client refer to the OpenFeature Go SDK documentation.
Evaluation details
The detailed getters of the OpenFeature client, such as BooleanValueDetails, report why an evaluation produced the value that it did:
| Outcome | Reason | Error code | Variant |
|---|---|---|---|
| A value was found | TARGETING_MATCH | The variation name, or the value ID | |
| A percentage rollout was skipped for a context without a targeting key | DEFAULT | The variation name, or the value ID | |
| The config carries no value | DEFAULT | ||
| The config key is unknown | ERROR | FLAG_NOT_FOUND | |
| No config state has arrived yet | ERROR | PROVIDER_NOT_READY | |
| The value does not match the requested type | ERROR | TYPE_MISMATCH |
The Variant is the name of the variation served, such as treatment, when the config has variations and that variation has a name. Otherwise it is ConfigDirector's ID for the value served, a stable hash you can send to analytics in place of the value itself; values served in offline mode have none. Before version 0.5.0 of the provider, the Variant was always the value ID, so an analytics tool that receives Variant now shows an experiment's evaluations under the variation names. In the last four cases, the in-code default value is returned.
details, err := client.BooleanValueDetails(ctx, "new-checkout", false, user)
if err != nil {
log.Printf("new-checkout fell back to its in-code default value: %s", details.ErrorCode)
}
To report an experiment to an analytics tool, follow the page for Amplitude, Mixpanel, Google Analytics 4, Segment or PostHog, which names the event that tool reads.
Context
The context is the last argument of every getter of the OpenFeature client. The OpenFeature Go provider evaluates targeting rules locally without additional network calls for different contexts.
import "github.com/open-feature/go-sdk/openfeature"
user := openfeature.NewEvaluationContext(
"12345", // In OpenFeature, the targeting key represents the context's identifier
map[string]any{
"name": "Example User",
// Any arbitrary traits which can be referenced in targeting rules
"traits": map[string]any{"region": "North America"},
},
)
booleanValue := client.Boolean(ctx, "my-config-key", false, user)
To evaluate flags for an entity other than a user, such as a tenant, set the context kind with a top-level kind attribute:
tenant := openfeature.NewEvaluationContext(
"acme",
map[string]any{
"kind": "tenant",
"name": "Acme Inc.",
"traits": map[string]any{"plan": "enterprise"},
},
)
booleanValue := client.Boolean(ctx, "my-config-key", false, tenant)
Leaving kind out means user. A kind inside traits is an ordinary trait, not the context kind. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and flags still resolve successfully, as if no context had been given. Context kinds are available from version 0.2.0 of the provider.
The evaluation context maps onto the ConfigDirector context as follows:
| OpenFeature evaluation context | ConfigDirector context |
|---|---|
The targeting key, or otherwise an id attribute | ID |
The top-level kind attribute | Kind |
The name attribute | Name |
The traits attribute, a map[string]any | Traits |
The anonymous attribute, a bool | Anonymous |
An evaluation context with neither a targeting key nor an id attribute skips percentage rollouts: a rollout does not apply to it, and the targeting rules after the rollout are tried, as they are after a conditional rule the context does not match. When none of them applies, the flag resolves to the default targeting rule value with the reason DEFAULT; a later rule that applies resolves with TARGETING_MATCH. A rule that serves a single value still applies to it. To keep an anonymous visitor in a rollout, give the context a stable targeting key, such as a session ID. Version 0.5.0 of the provider ended the evaluation at the skipped rollout and resolved to the default targeting rule value even when a later rule matched, and versions before 0.5.0 served every such context the first share of the rollout.
For additional information regarding the OpenFeature client refer to the OpenFeature Go SDK documentation.
Events
The provider emits PROVIDER_CONFIGURATION_CHANGED whenever configs are updated on the dashboard or via the admin API, carrying the keys of the configs in the update followed by the keys of the configs it removed:
logChangedFlags := func(details openfeature.EventDetails) {
log.Printf("Configs updated: %v", details.FlagChanges)
}
client.AddHandler(openfeature.ProviderConfigChange, &logChangedFlags)
When no config arrived in time at startup, the provider emits PROVIDER_READY once config arrives, as described in When no config arrives in time.
Track events
The provider implements OpenFeature's tracking API. client.Track reports to ConfigDirector that something happened in your application, such as a completed checkout, and ConfigDirector shows it on the Live feed and counts it for each variation of a running experiment; see Tracked events.
client.Track(
ctx,
"checkout-completed",
openfeature.NewEvaluationContext("user-123", nil),
openfeature.NewTrackingEventDetails(49.9).Add("plan", "pro").Add("seats", 3),
)
The value of the tracking event details is sent as the event's value, and their attributes as the event's details. The context the event happened for is the merged evaluation context: its targeting key, or otherwise its id attribute, and its kind.
A value of 0 is sent as no value, because OpenFeature Go has no way to say an event has none: attributes can only be added to details made with openfeature.NewTrackingEventDetails, so openfeature.NewTrackingEventDetails(0).Add("plan", "pro") sends the attributes alone.
An event counts for an experiment only when its evaluation context has the targeting key the experiment's flag was evaluated with, so track with the context you evaluate with. Without one, the event is still reported and counts for no experiment. For a context marked anonymous, the event is reported without the targeting key, so it counts for no experiment either.
The provider sends tracked events as the Go SDK does, with the same limits. Before version 0.5.0 of the provider, a Track call did nothing.
Test your code
Code that reads flags through OpenFeature is tested by swapping the provider, so it never has to change for a test and nothing from ConfigDirector is involved. The OpenFeature Go SDK ships an in-memory provider for that, memprovider, which serves the values your test sets.
Each flag is an InMemoryFlag with its named variants and the name of the variant it resolves to:
import (
"testing"
"github.com/open-feature/go-sdk/openfeature"
"github.com/open-feature/go-sdk/openfeature/memprovider"
"github.com/stretchr/testify/require"
)
func TestShowsTheNewCheckout(t *testing.T) {
provider := memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{
"new-checkout": {Key: "new-checkout", State: memprovider.Enabled, DefaultVariant: "on", Variants: map[string]any{"on": true, "off": false}},
"max-items": {Key: "max-items", State: memprovider.Enabled, DefaultVariant: "default", Variants: map[string]any{"default": int64(20)}},
})
require.NoError(t, openfeature.SetProviderAndWait(provider))
t.Cleanup(openfeature.Shutdown)
client := openfeature.NewClient("checkout")
require.True(t, client.Boolean(t.Context(), "new-checkout", false, openfeature.EvaluationContext{}))
require.Equal(t, int64(20), client.Int(t.Context(), "max-items", 0, openfeature.EvaluationContext{}))
}
The in-memory provider has no method to change a flag, so a test that changes a value mid-way sets a new provider with SetProviderAndWait. A flag can also carry a ContextEvaluator, a pointer to a function from the flag and the evaluation context to the value and its resolution details, for a test of code that targets specific users. The OpenFeature API is one global, so shut it down after each test with openfeature.Shutdown, as the cleanup above does, which lets the next test register its own provider. The examples use require from the testify module; the standard testing package works just as well.