---
title: "OpenFeature Go Provider"
description: "ConfigDirector Provider for the OpenFeature Go SDK"
canonical_url: "https://docs.configdirector.com/sdks/openfeature/go"
---
# OpenFeature Go Provider

> ConfigDirector Provider for the OpenFeature Go SDK

<div hidden="true" dataTitleIcon="openfeature-go">



</div>

<external-badges package-url="https://pkg.go.dev/github.com/ConfigDirector/go-sdks/configdirector-openfeature" registry="go" repo="go-sdks/tree/main/configdirector-openfeature">



</external-badges>

## Introduction

The OpenFeature Go Provider is intended to be used in combination with the [OpenFeature Go SDK](https://openfeature.dev/docs/reference/sdks/server/go/). The provider wraps the ConfigDirector [Go SDK](https://docs.configdirector.com/sdks/server/go).

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](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.

<code-group>

```bash [go get]
go get github.com/ConfigDirector/go-sdks/configdirector-openfeature@latest
```

</code-group>

## Configure and initialize the client

1. Create an instance of the provider using your server SDK key. You can retrieve a server SDK key for each environment under `SDK keys` in the dashboard's navigation panel. The provider starts connecting as soon as it is created.
2. Set the OpenFeature provider.
3. Get a client instance from OpenFeature.

```go [main.go]
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")
```

<warning>

Server SDK keys are secret values. Do not commit them to your source code repository. Provide them at runtime via environment variables instead.

</warning>

### 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`](https://docs.configdirector.com/sdks/server/go#additional-configuration-options), 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:

```go [main.go]
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:

```go [main.go]
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](https://docs.configdirector.com/sdks/server/go#additional-configuration-options). Handlers in `Hooks` run after the provider's own.

That includes [running without a connection](https://docs.configdirector.com/sdks/server/go#run-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:

```go [main.go]
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:

```go [main.go]
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:

<table>
<thead>
  <tr>
    <th>
      OpenFeature getter
    </th>
    
    <th>
      ConfigDirector config value
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        Boolean
      </code>
    </td>
    
    <td>
      Boolean
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        String
      </code>
    </td>
    
    <td>
      String, enum or URL
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Int
      </code>
      
      , <code>
        Float
      </code>
    </td>
    
    <td>
      Number
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Object
      </code>
    </td>
    
    <td>
      JSON object or JSON array
    </td>
  </tr>
</tbody>
</table>

`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`:

```go [main.go]
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](https://openfeature.dev/docs/reference/sdks/server/go/).

### Evaluation details

The detailed getters of the OpenFeature client, such as `BooleanValueDetails`, report why an evaluation produced the value that it did:

<table>
<thead>
  <tr>
    <th>
      Outcome
    </th>
    
    <th>
      Reason
    </th>
    
    <th>
      Error code
    </th>
    
    <th>
      Variant
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      A value was found
    </td>
    
    <td>
      <code>
        TARGETING_MATCH
      </code>
    </td>
    
    <td>
      
    </td>
    
    <td>
      The variation name, or the value ID
    </td>
  </tr>
  
  <tr>
    <td>
      A percentage rollout was skipped for a context without a targeting key
    </td>
    
    <td>
      <code>
        DEFAULT
      </code>
    </td>
    
    <td>
      
    </td>
    
    <td>
      The variation name, or the value ID
    </td>
  </tr>
  
  <tr>
    <td>
      The config carries no value
    </td>
    
    <td>
      <code>
        DEFAULT
      </code>
    </td>
    
    <td>
      
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      The config key is unknown
    </td>
    
    <td>
      <code>
        ERROR
      </code>
    </td>
    
    <td>
      <code>
        FLAG_NOT_FOUND
      </code>
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      No config state has arrived yet
    </td>
    
    <td>
      <code>
        ERROR
      </code>
    </td>
    
    <td>
      <code>
        PROVIDER_NOT_READY
      </code>
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      The value does not match the requested type
    </td>
    
    <td>
      <code>
        ERROR
      </code>
    </td>
    
    <td>
      <code>
        TYPE_MISMATCH
      </code>
    </td>
    
    <td>
      
    </td>
  </tr>
</tbody>
</table>

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.

```go [main.go]
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](https://docs.configdirector.com/integrations/analytics/amplitude), [Mixpanel](https://docs.configdirector.com/integrations/analytics/mixpanel), [Google Analytics 4](https://docs.configdirector.com/integrations/analytics/ga4), [Segment](https://docs.configdirector.com/integrations/analytics/segment) or [PostHog](https://docs.configdirector.com/integrations/analytics/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.

```go [main.go]
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:

```go [main.go]
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:

<table>
<thead>
  <tr>
    <th>
      OpenFeature evaluation context
    </th>
    
    <th>
      ConfigDirector context
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      The targeting key, or otherwise an <code>
        id
      </code>
      
       attribute
    </td>
    
    <td>
      <code>
        ID
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The top-level <code>
        kind
      </code>
      
       attribute
    </td>
    
    <td>
      <code>
        Kind
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The <code>
        name
      </code>
      
       attribute
    </td>
    
    <td>
      <code>
        Name
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The <code>
        traits
      </code>
      
       attribute, a <code>
        map[string]any
      </code>
    </td>
    
    <td>
      <code>
        Traits
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The <code>
        anonymous
      </code>
      
       attribute, a <code>
        bool
      </code>
    </td>
    
    <td>
      <code>
        Anonymous
      </code>
    </td>
  </tr>
</tbody>
</table>

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](https://openfeature.dev/docs/reference/sdks/server/go/).

## 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:

```go [main.go]
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](#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](https://docs.configdirector.com/monitoring/activity#tracked-events).

```go [main.go]
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](https://docs.configdirector.com/sdks/server/go#track-events) 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:

```go [checkout_test.go]
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.


## Sitemap

See the full [sitemap](https://docs.configdirector.com/sitemap.md) for all pages.
