---
title: "Go Server SDK"
description: "Evaluate configs and feature flags locally for any context with the Go server SDK, with updates delivered over server sent events"
canonical_url: "https://docs.configdirector.com/sdks/server/go"
---
# Go Server SDK

> Evaluate configs and feature flags locally for any context with the Go server SDK, with updates delivered over server sent events

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



</div>

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



</external-badges>

## Introduction

The Go Server SDK is a server-side SDK that evaluates configs and their targeting rules. Upon initialization, it retrieves configs and targeting rules from ConfigDirector services. From that point on, it evaluates configs locally for any context, and receives updates via server sent events (SSE) when configs are updated on the dashboard or via the admin API.

The minimum Go version supported is `1.26`.

The client is safe to share between goroutines. Create one when your application starts, share it for the lifetime of the process, and close it on shutdown. Evaluations read config state the client already holds in memory, so they make no network calls on the request path.

## Installation

The SDK can be installed with `go get`. Its package reference is on pkg.go.dev: [https://pkg.go.dev/github.com/ConfigDirector/go-sdks/configdirector](https://pkg.go.dev/github.com/ConfigDirector/go-sdks/configdirector)

<code-group>

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

</code-group>

## Configure and initialize the client

1. Create a client providing your server SDK key. You can retrieve a server SDK key for each environment under `SDK keys` in the dashboard's navigation panel. The client starts connecting as soon as it is created.
2. Wait for the client to be ready before serving requests.

```go [main.go]
import (
    "context"
    "log"

    "github.com/ConfigDirector/go-sdks/configdirector"
)

// IMPORTANT: Do not commit the server SDK key to your source code, it is a secret value.
// Creating the client starts its connection in the background.
client, err := configdirector.NewClient(configdirector.Options{SDKKey: "YOUR-SERVER-SDK-KEY"})
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// Blocks until the first config state arrives or the connection timeout elapses.
// If the wait times out, the client keeps connecting in the background and
// reads return their in-code default value until config state arrives.
if err := client.WaitForReady(context.Background()); err != nil {
    log.Printf("ConfigDirector is not ready yet: %v", err)
}
```

The client is safe to share between goroutines. Create one at startup, share it for the lifetime of the process, and call `Close` on shutdown.

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

`WaitForReady` blocks until the first config state arrives, the connection timeout elapses, or the context you pass ends, whichever comes first. It returns `nil` once the client is ready, `context.DeadlineExceeded` when the connection timeout elapsed first, the context's own error when it ended first, and `ErrClientClosed` when the client was closed. An error only says that the wait ended: the client keeps connecting in the background and becomes ready when config state arrives. Until then, every read returns its in-code default value. `Ready` reports whether config state has arrived.

### Additional configuration options

Every option is a field of the `Options` struct passed to `NewClient`. Only `SDKKey` is required, and only outside [offline mode](#run-without-a-connection); a zero value in any other field means the default described below. An option the client cannot use, such as a blank SDK key, an unknown connection mode, or a relative URL, is returned as an error from `NewClient` rather than as a client that quietly never updates.

#### `Metadata`

The `Metadata` option allows you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.

```go [main.go]
client, err := configdirector.NewClient(configdirector.Options{
    SDKKey:   "YOUR-SERVER-SDK-KEY",
    Metadata: configdirector.Metadata{AppName: "YOUR-APP-NAME", AppVersion: "1.0.2"},
})
```

#### `Logger`

The SDK logs through the standard library's `log/slog` package. By default it writes to `slog.Default()`, so it follows whatever handler and level your application configures. Every record carries the attribute `component=configdirector`, which makes the SDK's records easy to tell apart from your application's own.

Pass a `*slog.Logger` in the `Logger` option to send the SDK's records somewhere else, or to give them their own level:

```go [main.go]
import (
    "log/slog"
    "os"
)

logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))

client, err := configdirector.NewClient(configdirector.Options{
    SDKKey: "YOUR-SERVER-SDK-KEY",
    Logger: logger,
})
```

At the debug level the SDK logs every config update it receives.

#### `Connection`

The `Connection` option takes a `ConnectionOptions` struct with the following optional fields:

- `Mode`
  - The connection mode, one of `ConnectionModeStreaming`, `ConnectionModePolling` or `ConnectionModeOffline`. It is recommended to use the default of streaming unless you have a specific need to use polling instead. In offline mode the client never connects to ConfigDirector and serves the values you give it; see [Run without a connection](#run-without-a-connection).
  - Defaults to `ConnectionModeStreaming`
- `File`
  - The path of a JSON file holding the values to serve in offline mode, resolved against the working directory of the process. Only one of `File` and `Values` can be given, and only in offline mode. See [Run without a connection](#run-without-a-connection).
- `Values`
  - The values to serve in offline mode, as a `map[string]any` keyed by config key. Only one of `File` and `Values` can be given, and only in offline mode. See [Run without a connection](#run-without-a-connection).
- `PollingInterval`
  - Only used in polling mode. How long the client waits between polls of ConfigDirector services for updates, as a `time.Duration`. A value below the minimum of 1 minute is raised to 1 minute and a warning is logged. See [Polling intervals](https://docs.configdirector.com/getting-started/architecture#polling-intervals).
  - Defaults to 5 minutes
- `Timeout`
  - How long `WaitForReady` waits for the first config state, as a `time.Duration`. If the timeout is reached, `WaitForReady` returns `context.DeadlineExceeded` but the client is still not ready and returns in-code default values. The client will continue to attempt to connect and retrieve config values in the background. It has no effect in offline mode.
  - Defaults to 3 seconds
- `URL`
  - The base URL used to connect to ConfigDirector services
  - This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services. It has no effect in offline mode.
- `HTTPClient`
  - The `*http.Client` that sends every request. Provide one to control transport settings such as a corporate proxy or custom TLS. It has no effect in offline mode.
  - Defaults to `http.DefaultClient`

```go [main.go]
import "time"

client, err := configdirector.NewClient(configdirector.Options{
    SDKKey: "YOUR-SERVER-SDK-KEY",
    Connection: configdirector.ConnectionOptions{
        Mode:            configdirector.ConnectionModePolling,
        PollingInterval: 10 * time.Minute,
        Timeout:         5 * time.Second,
    },
})
```

#### `Telemetry`

Telemetry tuning. It is unlikely these settings need to be adjusted. However, in cases where your application has a large number of evaluations per second, you can adjust these settings to tune the memory footprint and frequency of telemetry requests.

Keep in mind that ConfigDirector relies on these telemetry events to provide insights and features related to the configs being used.

From version 0.5.0 of the SDK, each evaluation it reports says which variation was served and which percentage rollout and share served it. That is how ConfigDirector counts the contexts each variation of an experiment reached. [Tracked events](#track-events) are sent with the same reports.

The `Telemetry` option takes a `TelemetryOptions` struct with the following optional fields:

- `EventQueueLimit`
  - The size limit of telemetry event queues. If the size limit is reached before the events are flushed to the network, older events will be dropped.
  - ConfigDirector keeps a count of dropped events. If the number of dropped events is higher than 50% of the total events, ConfigDirector will issue an alert in the dashboard.
  - A number between 100 and 100,000. Defaults to 5,000.
- `FlushInterval`
  - How often events are flushed and sent over the network, as a `time.Duration`.
  - Decrease this number if your application consistently captures a large number of events in short periods of time in order to reduce memory footprint from a large event queue.
  - Defaults to 30 seconds.

```go [main.go]
import "time"

client, err := configdirector.NewClient(configdirector.Options{
    SDKKey:    "YOUR-SERVER-SDK-KEY",
    Telemetry: configdirector.TelemetryOptions{EventQueueLimit: 10_000, FlushInterval: 15 * time.Second},
})
```

### Hooks

Hooks are events you can subscribe to in order to be notified of some key actions from the client. In order to subscribe to hooks you can provide handlers in the `Hooks` option, which attaches them before the client can emit any event, or call the matching method on the client, which returns a function that cancels the registration:

```go [main.go]
unsubscribe := client.OnConfigsUpdated(func(update configdirector.ConfigsUpdated) {
    log.Printf("configs updated: %v", update.Keys)
})

unsubscribe() // Cancels the registration
```

```go [main.go]
client, err := configdirector.NewClient(configdirector.Options{
    SDKKey: "YOUR-SERVER-SDK-KEY",
    Hooks: configdirector.Hooks{
        OnConfigEvaluated: func(evaluation configdirector.Evaluation) {
            log.Printf("%s evaluated to %v", evaluation.Key, evaluation.Value)
        },
    },
})
```

The following hooks are available:

- `OnReady: func()`
  - Called when the client is initialized. When this event is emitted it means the client has received a payload from the ConfigDirector servers, or has loaded its [offline values](#run-without-a-connection), and is ready to evaluate configs. It is emitted once; a handler registered with `OnReady` after that point is called at once, on the calling goroutine.
- `OnConfigsUpdated: func(ConfigsUpdated)`
  - Called when a payload is received from the ConfigDirector servers with config data. It is emitted during initialization when an entire config payload is received, or when the [offline values](#run-without-a-connection) are loaded. After initialization, it is emitted when updates are pushed from the server (or discovered via polling if that connection mode is used).
  - `Keys []string` - The config keys that were included in the payload from the server, and the keys of configs whose targeting rules use a segment the payload included, sorted.
  - `RemovedKeys []string` - The keys of configs the payload removed, sorted. A config is removed when a full payload no longer includes it. Empty when nothing was removed.
- `OnConfigEvaluated: func(Evaluation)`
  - Called whenever a config is evaluated. This includes calls to the value methods and `Evaluate`, and evaluations delivered to watches.
  - `Evaluation` - A struct containing the details of the evaluation:
  
    - `Key string` - The config key that was evaluated
    - `Value any` - The value the config evaluated to, in the type the read asked for. It can be the in-code default value provided to the value method or to the watch. For example, if the config was evaluated before the client was initialized.
    - `ValueID string` - The value ID, a stable hash of the value that you can send to a third party rather than the `Value`. This can be useful for large values, like a JSON config, or to avoid disclosing the values themselves. It is empty when the evaluation fell back to the in-code default value. To report an experiment to an analytics tool, send the variation instead: the pages 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) and [PostHog](https://docs.configdirector.com/integrations/analytics/posthog) name the event each one reads.
    - `Variation *Variation` - The variation that was served, with its `ID` and `Name`. The `ID` stays the same when the variation is renamed, and `Name` is empty for a variation without one. It is `nil` when the config has no variations or the in-code default value is returned. Versions of the SDK before 0.5.0 do not report it.
    - `UsedDefault bool` - Whether or not the evaluation fell back to the in-code default value.
    - `Reason EvaluationReason` - The reason for the evaluation resolution. In the case the config successfully evaluated based on server-provided targeting rules, or served an offline value, it will be `EvaluationReasonFoundMatch`. A context without an `ID` that is served the default targeting rule value after skipping a percentage rollout reports `EvaluationReasonRolloutSkippedNoIdentifier`, with `UsedDefault` false; see [Contexts without an `ID`](#contexts-without-an-id). If the evaluation had to fall back to the in-code default value, the `Reason` will encode why the fallback was required:
    
      - `EvaluationReasonClientNotReady` - The evaluation happened before the client finished initialization, or after it was closed
      - `EvaluationReasonConfigStateMissing` - The requested config key was not present in the payload received from the server, usually because of an incorrect config key
      - `EvaluationReasonInvalidNumber` - The config was requested as a number but the value received from the server could not be read as that number type
      - `EvaluationReasonInvalidBoolean` - The config was requested as a boolean but the value received from the server was neither `true` nor `false`
      - `EvaluationReasonInvalidJSON` - The config was requested as JSON but the value received from the server could not be decoded into the target
      - `EvaluationReasonTypeMismatch` - The config was requested as a string but it is a boolean or number config
      - `EvaluationReasonValueMissing` - The config key was present in the payload received from the server, but it carried no value
    - `UserContext UserContext` - The context that was provided to the evaluation

Each reason constant's value is its name in kebab case, such as `type-mismatch` for `EvaluationReasonTypeMismatch`, which is how logs and the test client's documentation spell them.

`OnReady` and `OnConfigsUpdated` handlers run on the connection's goroutine, so one that blocks delays later updates. `OnConfigEvaluated` handlers run on the goroutine that read the value, or on the connection's goroutine when a watch fires. A panic in a handler is recovered and logged at error level; the other handlers and the connection continue.

### Run without a connection

Set the connection `Mode` to `ConnectionModeOffline` to run your application without connecting to ConfigDirector, for example in a suite of UI tests where each run pins every flag to a known value. An offline client needs no server SDK key, opens no connection and sends nothing, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no lifecycle state changes. Every context receives the same value and targeting rules are not applied.

Give the values in a JSON file, with one value per config key, or inline:

```go [main.go]
client, err := configdirector.NewClient(configdirector.Options{
    Connection: configdirector.ConnectionOptions{
        Mode: configdirector.ConnectionModeOffline,
        File: "flags/new-checkout-on.json",
    },
})
```

```json [flags/new-checkout-on.json]
{
  "new-checkout": true,
  "max-items": 20,
  "greeting": "hello",
  "theme": { "color": "blue" }
}
```

```go [main.go]
client, err := configdirector.NewClient(configdirector.Options{
    Connection: configdirector.ConnectionOptions{
        Mode:   configdirector.ConnectionModeOffline,
        Values: map[string]any{"new-checkout": true, "max-items": 20},
    },
})
```

The file path is resolved against the working directory of the process. The config type of each value in the file follows from the value itself: `true` or `false` (`boolean`), a number without a fractional part (`integer`), any other number (`float`), a string, or an object or array (`json`). Inline values follow the same rule with Go types, exactly as the [test client](#values) types them: a `bool`, any integer kind, a `float32` or `float64`, a `string`, or a map, slice, array or struct that encodes as JSON. A value read with an in-code default value of another type returns the in-code default value, as it does against ConfigDirector. The values are loaded before `NewClient` returns, so the client is ready at once: `WaitForReady` returns `nil` immediately, an `OnReady` handler given in `Hooks` runs during `NewClient`, and a watch never fires, because offline values never change. `PollingInterval`, `Timeout`, `URL` and `HTTPClient` have no effect.

With `ConnectionModeOffline` and neither `File` nor `Values`, the client is ready at once and every config returns its in-code default value.

`NewClient` returns an error, and no client, when the values cannot be loaded: the file is missing, cannot be read, is not a JSON object or holds a value such as `null`; an inline value is `nil` or of a type not listed above; `File` and `Values` are both given; or either is given in streaming or polling mode. A test run that starts from a misspelled path fails instead of passing on in-code default values.

If you come from LaunchDarkly, a file of values is what LaunchDarkly calls "flags from files", and `ConnectionModeOffline` with no values is its "offline mode".

## Retrieve config values

Retrieve config values via the typed value methods, and subscribe to updates via the typed watches. The first argument is the config key, the second is the in-code default value, which is returned if the config is not available or cannot be read as the given type, and the third is the context targeting rules are evaluated for. The method decides the type the config is read as:

```go [main.go]
user := configdirector.UserContext{ID: "user-id"}

// Retrieve config values
retries := client.IntValue("max-retries", 3, user)
theme := client.StringValue("theme", "light", user)
newCheckout := client.BoolValue("new-checkout", false, user)

// A JSON config is decoded into a value of your own, which holds the in-code default value
limits := map[string]any{"per_minute": 60}
if err := client.JSONValue("rate-limits", &limits, user); err != nil {
    log.Fatal(err)
}

// Watch for config updates
unwatch := client.WatchBool("new-checkout", false, user, func(value bool) {
    log.Printf("new-checkout is now %t", value)
})

// Call unwatch when the watch is no longer needed
unwatch()
```

The type a config is read as is decided by the method you call, not by how the config was declared in the dashboard. There is one method per type the SDK can read, so a type it cannot fill is a compile error rather than a surprise at runtime. Each one takes the value to return when the config is missing, the client is not ready, or the value will not read as the requested type, so the in-code default value should always be the safe choice:

- `BoolValue(key string, defaultValue bool, userContext UserContext) bool`
- `StringValue(key string, defaultValue string, userContext UserContext) string`
- `IntValue(key string, defaultValue int64, userContext UserContext) int64`
- `FloatValue(key string, defaultValue float64, userContext UserContext) float64`
- `JSONValue(key string, target any, userContext UserContext) error`

A few of those are worth calling out:

- Reading a string, enum, URL or JSON config as a string returns the value as the server spelled it, with no parsing, so a JSON config gives its JSON. A boolean or number config read as a string gives the in-code default value instead.
- Only `true` and `false` read as a boolean, in either casing. A config holding `1` yields the in-code default value.
- A whole number the server wrote as `26.0` or `2.6e1` still reads as `26`. A value an `int64` cannot hold yields the in-code default value rather than an overflow.

Every value method has a `ValueDetails` twin, such as `BoolValueDetails`, that also returns an `EvaluationDetails` with the `Reason`, `ValueID`, `UsedDefault` and `Variation` of the read, so your code can tell a served value from a fallback:

```go [main.go]
newCheckout, details := client.BoolValueDetails("new-checkout", false, user)
if details.UsedDefault {
    log.Printf("new-checkout fell back to its in-code default value: %s", details.Reason)
}
```

<note>

Value methods never return an error when a config is missing or a value will not read as the requested type; they return your in-code default value instead. Which of those happened is reported by the `ValueDetails` twins and through `OnConfigEvaluated`.

</note>

### JSON configs

`JSONValue` decodes the config's JSON document into `target`, a non-nil pointer to a struct, map, slice or any other type `encoding/json` can decode into. The value you put in the target beforehand is the in-code default value: the target is left as it was when the config is missing, the client is not ready, or the document cannot be decoded into it. The only error is for a target that is not a non-nil pointer.

```go [main.go]
type RateLimits struct {
    PerMinute int `json:"per_minute"`
}

limits := RateLimits{PerMinute: 60}
if err := client.JSONValue("rate-limits", &limits, user); err != nil {
    log.Fatal(err)
}
```

<note>

`encoding/json` ignores any member the target does not declare, and leaves a field the document does not carry as it was, so a config whose shape has moved on cannot be told apart from your in-code default value. Decode into a `map[string]any` to read the document as it stands.

</note>

### Evaluate config values with a context

<note>

Unlike client SDKs, the server SDKs are able to evaluate targeting rules for the given context locally without additional network calls.

</note>

Every value method takes a `UserContext` as its last argument, which is what targeting rules are evaluated against. The same key can therefore resolve differently per user. Pass an empty `configdirector.UserContext{}` when there is no user to evaluate for.

The context is the last argument of every value method. Unlike client SDKs, the server SDKs are able to evaluate targeting rules for the given context locally without additional network calls.

```go [main.go]
import "github.com/ConfigDirector/go-sdks/configdirector"

user := configdirector.UserContext{
    ID:   "12345",
    Name: "Example User",
    Traits: map[string]any{
        "region": "North America", // Any arbitrary traits which can be referenced in targeting rules
    },
}

client.BoolValue("my-boolean-config-key", false, user)
```

It is also the third argument of every watch:

```go [main.go]
unwatch := client.WatchBool("new-checkout", false, user, func(value bool) {
    log.Printf("new-checkout is now %t", value)
})
```

To evaluate configs for an entity other than a user, such as a tenant, set the context kind with `Kind`:

```go [main.go]
tenant := configdirector.UserContext{
    ID:   "acme",
    Kind: "tenant",
    Name: "Acme Inc.",
    Traits: map[string]any{
        "plan": "enterprise",
    },
}

client.BoolValue("my-boolean-config-key", false, tenant)
```

Leaving `Kind` empty means `user`. 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 configs are evaluated as if no context had been given. Context kinds are available from version 0.3.0 of the SDK.

`UserContext` is a struct with the following fields:

- `ID`
  - The context's identifier. With the context kind, it decides the context's bucket in a percentage rollout, so changing it can move the context into a different bucket. A context without one skips percentage rollouts; see [Contexts without an `ID`](#contexts-without-an-id).
- `Kind`
  - The context kind, such as `tenant`. Contexts of different kinds are separate contexts even when they share an identifier, and a percentage rollout can place them in different shares.
- `Name`
  - The context's display name.
- `Traits`
  - A `map[string]any` of arbitrary traits which can be referenced in targeting rules, keyed by the name the rule references. Each trait is evaluated as the value `encoding/json` encodes it to: an `int` is a number, a `[]string` is an array of text, a struct is an object keyed by its JSON field names, and a `time.Time` is its RFC 3339 text. A trait `encoding/json` cannot encode, such as a channel, matches no condition, and the other traits in the context still match.
- `Anonymous`
  - Keeps the context out of the dashboard: it is evaluated but never persisted, and telemetry reports neither the context nor its ID.

```go [main.go]
user := configdirector.UserContext{
    ID:   "user-id",
    Name: "Example User",
    Traits: map[string]any{
        "region": "North America",
        "age":    26,
        "tags":   []string{"beta", "internal"},
    },
}
```

#### Contexts without an `ID`

A percentage rollout places each context in a share by its `ID`, so a context without an `ID` 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. The default targeting rule value is served when none of them applies. A rule that serves a single value still applies to it. To keep an anonymous visitor in a rollout, give the context a stable `ID`, such as a session ID. Version 0.5.0 of the SDK ended the evaluation at the skipped rollout and served the default targeting rule value even when a later rule matched, and versions before 0.5.0 served every context without an `ID` the first share of the rollout.

### Watch for updates

The watches mirror the value methods, one per type. Each accepts the config key, the in-code default value used when an update will not read as that type, the context, and a handler that runs with the newly evaluated value:

- `WatchBool(key string, defaultValue bool, userContext UserContext, handler func(bool))`
- `WatchString(key string, defaultValue string, userContext UserContext, handler func(string))`
- `WatchInt(key string, defaultValue int64, userContext UserContext, handler func(int64))`
- `WatchFloat(key string, defaultValue float64, userContext UserContext, handler func(float64))`
- `WatchJSON(key string, newTarget func() any, userContext UserContext, handler func(target any))`

A watch fires whenever an update carries its key or a segment the config's targeting rules use, whether or not the value changed. Registering a watch before the first config state arrives means it is called for that first state as well; one registered afterwards only sees later updates, so a watch on a client in [offline mode](#run-without-a-connection) never fires. When a full payload no longer includes the watched config, the handler is called with the in-code default value, so it always agrees with what the value method would return. Handlers run on the connection's goroutine, so one that blocks delays later updates.

```go [main.go]
unwatch := client.WatchBool(
    "new-checkout",
    false,
    configdirector.UserContext{ID: "user-id", Name: "Example User", Traits: map[string]any{"region": "North America"}},
    func(value bool) {
        log.Printf("new-checkout is now %t", value)
    },
)
```

`WatchJSON` takes a function that returns a fresh pointer holding the in-code default value, rather than the value itself, because every update decodes into a new target:

```go [main.go]
unwatch := client.WatchJSON(
    "rate-limits",
    func() any { return &RateLimits{PerMinute: 60} },
    user,
    func(target any) {
        limits := target.(*RateLimits)
        log.Printf("rate-limits is now %d per minute", limits.PerMinute)
    },
)
```

Each watch returns a function that cancels it. Calling it twice is harmless.

## Track events

`Track` reports to ConfigDirector that something happened in your application, such as a completed checkout. ConfigDirector shows tracked events on the Live feed and counts them for each variation of a running experiment; see [Tracked events](https://docs.configdirector.com/monitoring/activity#tracked-events).

`Track` takes the name of the event, the context the event happened for, and `TrackOptions` with a `Value` and `Details`. Go has no optional arguments, so `configdirector.UserContext{}` means no context and `configdirector.TrackOptions{}` means no value or details:

```go [main.go]
import "encoding/json"

client.Track("checkout-completed", configdirector.UserContext{ID: "user-id"}, configdirector.TrackOptions{
    Value: json.Number("49.90"),
    Details: configdirector.TrackedEventDetails{
        "plan":    "pro",
        "seats":   3,
        "tags":    []string{"beta", "internal"},
        "address": map[string]any{"city": "Lisbon"},
    },
})

client.Track("export-finished", configdirector.UserContext{ID: "acme", Kind: "tenant"}, configdirector.TrackOptions{})

client.Track("nightly-sync-finished", configdirector.UserContext{}, configdirector.TrackOptions{})
```

- `Value` is a number the event measures, such as an amount of money, a count or a duration. It takes any integer or float kind, a `json.Number`, or a type whose `MarshalText` writes a JSON number, such as a `*big.Int`, a `*big.Float` or a decimal library's type. It is sent as written, without rounding, so `json.Number("49.90")` arrives as `49.90`. A `time.Duration` is sent as its number of nanoseconds.
- `Details` is a map describing the event. Its values are strings, numbers, booleans, or nested maps and slices, and it accepts anything else `encoding/json` can write, such as a struct or a `time.Time`. A number that is not finite is sent as null inside a `map[string]any` or a `[]any`; anywhere else, such as in a struct field, it leaves the details out.

An event counts for an experiment only when it is tracked for a context with an `ID`, the same one the experiment's config was evaluated for, so pass the context you evaluate with when you track the outcome of an experiment. With `configdirector.UserContext{}`, or for a context without an `ID`, the event is still reported and counts for no experiment. For a context marked `Anonymous`, the event is reported without the `ID`, so it counts for no experiment either. A context with an invalid context kind is ignored as it is in an evaluation: the SDK logs an error and reports the event without a context.

`Track` returns nothing and never panics. The event is sent with the SDK's next telemetry report, every 30 seconds unless you changed [`FlushInterval`](#telemetry). In [offline mode](#run-without-a-connection) and after `Close`, `Track` does nothing. The SDK applies these limits, and logs one warning for each of them per telemetry report:

<table>
<thead>
  <tr>
    <th>
      Limit
    </th>
    
    <th>
      Beyond it
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      An event name of 1 to 150 characters
    </td>
    
    <td>
      The event is not reported.
    </td>
  </tr>
  
  <tr>
    <td>
      1,000 tracked events in one telemetry report
    </td>
    
    <td>
      Further events are not reported until that report is sent.
    </td>
  </tr>
  
  <tr>
    <td>
      Details of up to 20 top-level keys and 1 KB as JSON, holding only values <code>
        encoding/json
      </code>
      
       can write
    </td>
    
    <td>
      The details are left out and the event is still reported.
    </td>
  </tr>
  
  <tr>
    <td>
      A <code>
        Value
      </code>
      
       that is a finite number
    </td>
    
    <td>
      The value is left out and the event is still reported.
    </td>
  </tr>
</tbody>
</table>

ConfigDirector applies limits of its own to the events it stores; see [Limits](https://docs.configdirector.com/monitoring/activity#limits).

`Track` is available from version 0.5.0 of the SDK, which exports the `TrackOptions`, `TrackedEventDetails` and `TrackedEventDetailValue` types.

## Other useful client features

The client provides additional methods.

### `Evaluate`

Evaluates a config the way the value methods do and returns the `Evaluation` behind it — the value, whether it is the in-code default value, the `Reason`, the `ValueID`, the `Variation`, and the `UserContext` — instead of the value alone. The type of the in-code default value decides how the config is read: a `bool`, a `string`, any integer kind, a `float32` or `float64`, or a map, slice, array or struct for a JSON document. `Value` holds that same type, and a map or struct takes only a JSON object, and a slice or array only a JSON array. It is the same struct the [`OnConfigEvaluated` hook](#hooks) reports, so use it where the reason matters at the point of the read, such as when reporting an evaluation to another system; the value methods are enough everywhere else. Like every read, it reaches `OnConfigEvaluated` and is counted in telemetry.

```go [main.go]
evaluation, err := client.Evaluate("my-config-key", false, configdirector.UserContext{ID: "user-id"})
if err != nil {
    log.Fatal(err)
}
if evaluation.Reason == configdirector.EvaluationReasonConfigStateMissing {
    log.Print("No config with this key reached the SDK.")
}
```

The only errors are for a blank key and for an in-code default value it cannot read, such as `nil`, a pointer, a channel or a func. When it returns an error, the evaluation is empty and nothing is reported.

`Evaluate` is available from version 0.5.0 of the SDK.

### `Ready`

Returns a boolean indicating if the client has received config state and is ready to evaluate configs. It is initially `false` and becomes `true` once the first config state arrives. Until it does, every read returns its in-code default value.

### `Closed`

Returns a boolean indicating if the client has been closed. A closed client cannot be reopened.

### `AllConfigs`

Returns the evaluated state of every config the client holds as a `[]ConfigState` sorted by key, each with the config's `ID`, `Key`, `Type`, `Value` as the server spelled it, `ValueID` and `Variation`. When a percentage rollout served the value, it also carries the rollout's `RuleID` and `ShareID`. It takes the context to evaluate for and, optionally, the config keys to restrict the result to. It is empty until the client is ready.

This is intended for handing state to a client SDK to hydrate with. It records no telemetry and reaches no `OnConfigEvaluated` handler, since the SDK that receives the state reports its own evaluations.

`Variation`, `RuleID` and `ShareID` are available from version 0.5.0 of the SDK.

### `UnwatchAll`

Cancels every watch on every config. Handlers registered with `OnReady`, `OnConfigsUpdated` and `OnConfigEvaluated` stay.

### `Close`

Closes the connection to ConfigDirector services, reports whatever telemetry is pending, and cancels every watch and event handler. After `Close` the client is not ready and every read returns its in-code default value. Calling `Close` more than once is harmless and returns the first call's result.

Only close when your application shuts down and it will no longer make use of the client.

<warning>

Never create a client inside a request handler. Each one opens its own connection to ConfigDirector, starts out not ready so it serves the in-code default values, and keeps connecting in the background for as long as it lives.

</warning>

## Test your code

Use the SDK's `configdirectortest` package to test the code that reads your configs and flags. It creates a **test client**: the SDK's real client wired to an in-memory connection that your test controls. Only the connection to ConfigDirector and the telemetry are replaced. Everything else is the same code that runs in production, so the code under test behaves exactly as it does against ConfigDirector, and no network connection is opened, no telemetry is sent, and no goroutine is started. The package ships in the module, so there is nothing else to install.

```go [checkout_service_test.go]
import (
    "testing"

    "github.com/ConfigDirector/go-sdks/configdirector/configdirectortest"
    "github.com/stretchr/testify/require"
)

func TestNewCheckout(t *testing.T) {
    testClient := configdirectortest.NewTestClient(map[string]any{"new-checkout": true, "max-items": 20})
    t.Cleanup(func() { require.NoError(t, testClient.Close()) })
    service := NewCheckoutService(testClient.Client())

    require.True(t, service.IsNewCheckoutEnabled("user-123"))

    require.NoError(t, testClient.SetValue("new-checkout", false))
    require.False(t, service.IsNewCheckoutEnabled("user-123"))
}
```

`testClient.Client()` is a `*configdirector.Client`, so it goes anywhere your code accepts one. It is ready when `NewTestClient` returns, with the values delivered as its first update, so the code under test can read at once; `HoldInitialization()` keeps it not ready instead, for testing what your code does before config state arrives. Pass the client to the code under test as a parameter, as `NewCheckoutService` does above, rather than reaching for a package-level one: that is what lets the test hand it a client it controls. The examples use `require` from the testify module; the standard `testing` package works just as well.

### Values

`NewTestClient`, `SetValue` and `ReplaceValues` take Go values, and the config type follows from each value: a `bool`; any integer kind, `time.Duration` included (an integer config); a `float32` or `float64` (a float config); a `string`; or a map, slice, array or struct (a JSON config holding what `encoding/json` writes for it). A `string` is always a string config, so JSON text meant as a JSON config is given as a `json.RawMessage`. Every value is served as an unconditional config, so every context receives the same value; a test that needs different values per context is written as one test per value. A `nil` value, a blank key, a non-finite number, a value that does not encode as JSON, or a value of any other kind, such as a pointer or a channel, is an error from `SetValue` and `ReplaceValues` and a panic from `NewTestClient`; in every case nothing changes.

Reads behave as they do in production: `SetValue("k", true)` read with `StringValue` returns the in-code default value with the `type-mismatch` reason, `SetValue("k", 2.5)` read with `IntValue` returns the default with the `invalid-number` reason, and `SetValue("k", "")` serves the in-code default value with the `value-missing` reason. The `ValueDetails` methods and `OnConfigEvaluated` handlers report the reason.

### Controls

<table>
<thead>
  <tr>
    <th>
      Control
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        SetValue(key, value)
      </code>
    </td>
    
    <td>
      Stores the value and, once the client has received its first update, delivers an update carrying only <code>
        key
      </code>
      
      . Watches of <code>
        key
      </code>
      
      , <code>
        OnConfigsUpdated
      </code>
      
       handlers and reads see it before the call returns.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        RemoveValue(key)
      </code>
    </td>
    
    <td>
      Removes the value and delivers a full update without it. Reads return the in-code default value with the <code>
        config-state-missing
      </code>
      
       reason, watches of <code>
        key
      </code>
      
       receive the default, and <code>
        OnConfigsUpdated
      </code>
      
       lists <code>
        key
      </code>
      
       in <code>
        RemovedKeys
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ReplaceValues(values)
      </code>
    </td>
    
    <td>
      Replaces every stored value and delivers a full update. Use it to reset a test client shared across tests.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        CompleteInitialization()
      </code>
    </td>
    
    <td>
      Delivers the stored values to a client built with <code>
        HoldInitialization()
      </code>
      
      , on the calling goroutine, so the client is ready and a blocked <code>
        WaitForReady
      </code>
      
       has returned when the call returns. On a ready client it does nothing.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        FailInitialization()
      </code>
    </td>
    
    <td>
      Fails the held initialization the way a refused SDK key does: the failure is logged at error level and the client stays not ready, so reads return the in-code default value with the <code>
        client-not-ready
      </code>
      
       reason and a <code>
        WaitForReady
      </code>
      
       in flight ends with its timeout or its context. <code>
        CompleteInitialization()
      </code>
      
       still delivers the stored values afterwards. On a ready client it does nothing.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        TrackedEvents()
      </code>
    </td>
    
    <td>
      Returns the events the code under test tracked with <code>
        Track
      </code>
      
      , in call order, each as a <code>
        configdirectortest.TrackedEvent{Name, UserContext, Value, Details}
      </code>
      
      . An event whose name the SDK would not report is not recorded, and a value or details the SDK would leave out are <code>
        nil
      </code>
      
       in the record. The limit of 1,000 events per telemetry report does not apply to the record. <code>
        Value
      </code>
      
       is what the code under test gave, and <code>
        Details
      </code>
      
       keep the Go type of each value, so details of <code>
        map[string]any{"seats": 3}
      </code>
      
       compare equal to that same map. Holding the returned slice does not show later events, so call it again for them. <code>
        ReplaceValues
      </code>
      
       leaves the record as it is.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ClearTrackedEvents()
      </code>
    </td>
    
    <td>
      Forgets every event recorded so far. A test client shared across tests needs this and <code>
        ReplaceValues
      </code>
      
       to reset.
    </td>
  </tr>
</tbody>
</table>

```go [checkout_service_test.go]
import "time"

testClient := configdirectortest.NewTestClient(
    map[string]any{"new-checkout": true},
    configdirectortest.HoldInitialization(),
    configdirectortest.WithTimeout(500*time.Millisecond),
)
t.Cleanup(func() { require.NoError(t, testClient.Close()) })
service := NewCheckoutService(testClient.Client())
testClient.FailInitialization()

require.False(t, testClient.Client().Ready())
require.False(t, service.IsNewCheckoutEnabled("user-123"))
```

### Options

`NewTestClient(values, options...)` takes `HoldInitialization()`, described above; `WithTimeout`, the client's connection timeout, which bounds how long a held `WaitForReady` waits and defaults to the SDK's production timeout; `WithLogger`, which defaults to `slog.Default()` as for a production client; and `WithHooks`, handlers attached before the first update as `Options.Hooks` attaches them, so an `OnConfigsUpdated` hook sees the values arrive and an `OnReady` hook sees the client become ready.

### What to expect

- Watches and handlers run on the goroutine that calls `NewTestClient`, `SetValue`, `RemoveValue`, `ReplaceValues` or `CompleteInitialization`, not on a connection goroutine, so an assertion can follow the call directly. A change made from inside a handler is delivered after the update being handled, as it would be by the single connection goroutine in production.
- The first update fires `OnConfigsUpdated` before `OnReady`, as in production. With `HoldInitialization()`, handlers and watches registered before `CompleteInitialization` see it.
- A held `WaitForReady` that times out leaves the client not ready, and `CompleteInitialization` afterwards still makes it ready, as production does when config state arrives after the wait.
- Watches fire on every update carrying their key, whether or not the value changed, as in production. `RemoveValue` and `ReplaceValues` deliver a full update, so they also fire the watches of every remaining key.
- A panic in a watch or handler is recovered and logged, as it is in production. A failed `require` assertion inside a handler ends the test as it does anywhere else, because the handler runs on the test's goroutine.
- After `Close`, reads return the in-code default value with the `client-not-ready` reason, every handler and watch is canceled, `Track` records nothing, the controls store without delivering, and no goroutine is left running, because none was started.


## Sitemap

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