> ## Documentation Index
> Fetch the complete documentation index at: https://launchdarkly.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK reference

<View title="Developer" />

<View title="Federal docs" />

<View title="EU docs" />

This topic documents how to get started with the Go SDK, and links to reference information on all of the supported features.

<Note>
  **SDK quick links**

  LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and a sample application:

  <table>
    <thead>
      <tr>
        <th>Resource</th>
        <th>Location</th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td>SDK API documentation</td>
        <td>[SDK API docs](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7)</td>
      </tr>

      <tr>
        <td>Supported SDK Versions</td>
        <td>[Go server SDK](/docs/sdk/concepts/supported-versions#go-server-sdk)</td>
      </tr>

      <tr>
        <td>GitHub repository</td>
        <td>[go-server-sdk](https://github.com/launchdarkly/go-server-sdk)</td>
      </tr>

      <tr>
        <td>Sample application</td>
        <td>[Go](https://github.com/launchdarkly/hello-go)</td>
      </tr>

      <tr>
        <td>Published module</td>
        <td>[pkg.go.dev](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7)</td>
      </tr>
    </tbody>
  </table>
</Note>

<Note>
  **SDK version compatibility**

  The LaunchDarkly Go SDK, version 7.10 and higher, is compatible with Go 1.23 and higher.

  The LaunchDarkly Go SDK, version 7.0 through 7.9, is compatible with Go 1.20 and higher.

  The LaunchDarkly Go SDK, version 6.x, is compatible with Go 1.18 and higher.
</Note>

## Get started

After you complete the [Getting Started process](/docs/home/getting-started), follow these instructions to start using the LaunchDarkly SDK in your Go application.

### Install the SDK

First, install the LaunchDarkly SDK as a dependency in your application. How you do this depends on what dependency management system you are using:

* If you are using the standard [Go modules](https://github.com/golang/go/wiki/Modules) system, import the SDK packages in your code and `go build` will automatically download them. The SDK and its dependencies are modules.
* Otherwise, use the `go get` command and specify the SDK version, such as `go get github.com/launchdarkly/go-server-sdk/v7`.

There are several packages that you can import, depending on which features you are using. We recommend following:

<CodeGroup>
  ```go title="Go SDK v7" maxLines=0 expandable lines wrap theme={null}
  import (
      // go-sdk-common/v3/ldcontext defines LaunchDarkly's model for contexts
      "github.com/launchdarkly/go-sdk-common/v3/ldcontext"

      // go-sdk-common/v3/ldmigration defines LaunchDarkly's model for migration feature flags
      // (only needed if you are working with migration flags)
      "github.com/launchdarkly/go-sdk-common/v3/ldmigration"

      // go-server-sdk/v7 is the main SDK package - here we are aliasing it to "ld"
      ld "github.com/launchdarkly/go-server-sdk/v7"

      // go-server-sdk/v7/ldcomponents is for advanced configuration options
      "github.com/launchdarkly/go-server-sdk/v7/ldcomponents"

      // go-server-sdk/v7/ldplugins allows you to add plugins to the main SDK
      "github.com/launchdarkly/go-server-sdk/v7/ldplugins"

      // observability-sdk/go is the observability plugin - here we are aliasing it to "ldobserve"
      // this package requires go-server-sdk/v7 version 7.11 or later
      ldobserve "github.com/launchdarkly/observability-sdk/go"
  )
  ```
</CodeGroup>

It is good practice to pin your dependencies to a specific version. Refer to the [SDK releases page](https://github.com/launchdarkly/go-server-sdk/releases) to identify the latest version. When you update your version of `go-server-sdk`, you should also update `go-sdk-common`.

### Initialize the client

After you install and import the SDK, you have two options:

* Create an instance of [`LDScopedClient`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#LDScopedClient). This is a wrapper around `LDClient` that lets you specify the [evaluation context](/docs/home/flags/contexts#about-contexts) to use for all operations, so you do not need to specify a context for each method call. The scoped client's context is a [multi-context](/docs/home/flags/multi-contexts), and you can update the multi-context with additional or updated associated contexts any time.
* Create a single, shared instance of [`LDClient`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#LDClient). This client requires that you specify an [evaluation context](/docs/home/flags/contexts#about-contexts) in each method call.

<Warning>
  **LDScopedClient is in beta**

  `LDScopedClient` is in beta. It is still undergoing testing and active development. Its functionality may change without notice, including becoming backwards incompatible.
</Warning>

Both options require that you specify your SDK key. The SDK key authorizes your application to connect to a particular environment within LaunchDarkly.

<Note>
  **The Go SDK uses an SDK key**

  The Go SDK uses an SDK key. Keys are specific to each project and environment. They are available on the **SDK keys** page under **Settings**. To learn more about key types, read [Keys](/docs/sdk/concepts/client-side-server-side#keys-and-credentials).
</Note>

<Warning>
  **LDClient must be a singleton**

  It's important to make the `LDClient` a singleton for each LaunchDarkly project. The client instance maintains internal state that allows LaunchDarkly to serve feature flags without making any remote requests. Do not instantiate a new client with every request.

  If you use `LDScopedClient`, you should create a new scoped client for each logical scope for your context or multi-context. For example, you might create a new scoped client for each web request. Each scoped client should use the same `LDClient` instance in its initialization.

  If you have multiple LaunchDarkly projects, you can create one `LDClient` for each. In this situation, the clients operate independently. For example, they do not share a single connection to LaunchDarkly.
</Warning>

This example assumes you've imported the LaunchDarkly SDK package as `ld`, as shown above.

<CodeGroup>
  ```go title="Go SDK, using LDScopedClient" maxLines=0 lines wrap theme={null}
  client, _ := ld.MakeCustomClient("YOUR_SDK_KEY",
    ld.Config{
      // optional observability plugin, requires Go SDK v7.11+
      Plugins: []ldplugins.Plugin{
        ldobserve.NewObservabilityPlugin(),
      },
    }, 5*time.Second)

  context := ldcontext.NewBuilder("example-context-key").
      Name("Sandy").
      Build()

  scopedClient := ld.NewScopedClient(client, context)
  ```

  ```go title="Go SDK, using LDClient" lines wrap theme={null}
    client, _ := ld.MakeCustomClient("YOUR_SDK_KEY",
      ld.Config{
        // optional observability plugin, requires Go SDK v7.11+
        Plugins: []ldplugins.Plugin{
          ldobserve.NewObservabilityPlugin(),
        },
      }, 5*time.Second)
  ```

  ```go title="Go SDK, using LDClient and default configuration" lines wrap theme={null}
  client, _ := ld.MakeClient("YOUR_SDK_KEY", 5*time.Second)
  ```
</CodeGroup>

The final argument to `MakeClient` or `MakeCustomClient` is a timeout parameter. In these examples, you are telling the SDK that it can spend up to five seconds attempting to connect to LaunchDarkly services before returning to your application. For more details about what the timeout means and what happens if initialization fails, read [`MakeClient`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#MakeClient) and [`MakeCustomClient`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#MakeCustomClient).

To learn more about the observability plugin, read [Go SDK observability reference](/docs/sdk/observability/go). To learn more about the specific configuration options available for this SDK, read [`Config`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#Config).

<Tip>
  **Best practices for error handling**

  The second return type in these code samples ( `_` ) represents an error in case the LaunchDarkly client does not initialize. Consider naming the return value and using it with proper error handling.
</Tip>

### Evaluate a context

After you initialize the client, you can check which variation a particular context should receive for a given feature flag. If you are using `LDScopedClient`, you create the scoped client with the context, and then evaluate the flag. If you are using `LDClient`, you pass the context to the flag evaluation method.

Here's how:

<CodeGroup>
  ```go title="Go SDK v7.13.4+, using LDScopedClient" expandable lines wrap theme={null}
  import (
      "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
  )

  flagKey := "example-flag-key"
  context := ldcontext.NewBuilder("example-context-key").
      Name("Sandy").
      Build()

  scopedClient := ld.NewScopedClient(client, context)
  // LDScopedClient is in beta and may change without notice.

  showFeature, _ := scopedClient.BoolVariation(flagKey, false)
  if showFeature {
      // Application code to show the feature
  } else {
      // The code to run if the feature is off
  }
  ```

  ```go title="Go SDK v6+, using LDClient" lines wrap theme={null}
  import (
      "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
  )

  flagKey := "example-flag-key"
  context := ldcontext.NewBuilder("example-context-key").
      Name("Sandy").
      Build()

  showFeature, _ := client.BoolVariation(flagKey, context, false)
  if showFeature {
      // Application code to show the feature
  } else {
      // The code to run if the feature is off
  }
  ```
</CodeGroup>

To learn more, read [Flag variation evaluation](/docs/sdk/features/evaluating) and [Flag variation evaluation details](/docs/sdk/features/evaluation-reasons). For more information about how contexts are specified, read [Context configuration](/docs/sdk/features/context-config).

#### Use Go contexts with LDScopedClient

As [described above](#initialize-the-client), one advantage of using `LDScopedClient` is that you can specify the [evaluation context](/docs/home/flags/contexts#about-contexts) to use for all operations, and do not need to specify a context for each method call. You can update the scoped client's current context with additional or updated associated contexts any time.

After you create a scoped client, we recommend adding it your Go context. Another advantage of using `LDScopedClient` is that you can pass the scoped client to any logic that already takes a Go context (`context.Context`), using utility methods provided in the SDK. This means the scoped client is implicitly passed around through all of your code that uses `context.Context`, and you can access the scoped client anywhere in your application logic.

Here's how to add and retrieve your `LDScopedClient` from your Go context:

<CodeGroup>
  ```go title="Add LDScopedClient to Go context" lines wrap theme={null}
  scopedClient := ld.NewScopedClient(client, ldContext)
  ctx := ld.GoContextWithScopedClient(context.Background(), scopedClient)
  otherFunction(ctx)
  // LDScopedClient is in beta and may change without notice.
  ```

  ```go title="Retrieve LDScopedClient from Go context" expandable lines wrap theme={null}
    // GetScopedClient returns the scoped client from the Go context
    // If a scoped client is not present, it returns nil and false

    func logicWithFeatureFlag(ctx context.Context) {
      scopedClient, ok := ld.GetScopedClient(ctx)
      isFeatureEnabled := false // default value if scoped client is not available
      if ok {
        isFeatureEnabled, err = scopedClient.BoolVariation("example-flag-key", false)
        // handle err as appropriate...
      }
    }

    // MustGetScopedClient also returns the scoped client from the Go context
    // If a scoped client is not present, it panics

    func logicWithFeatureFlag(ctx context.Context) {
      scopedClient := ld.MustGetScopedClient(ctx)
      isFeatureEnabled, err := scopedClient.BoolVariation("example-flag-key", false)
        // handle err as appropriate...
    }

  ```
</CodeGroup>

An example of how this might apply in your application is if you have HTTP middleware, and you want to pass an `LDScopedClient` into the `http.Request`'s Go context:

<CodeGroup>
  ```go title="Example: Using LDScopedClient in Go context" lines wrap theme={null}
  func LDScopedClientMiddleware(client *LDClient) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
          scopedClient := NewScopedClient(client, ldcontext.New("example-context-key"))
          ctx := GoContextWithScopedClient(r.Context(), scopedClient)
          next.ServeHTTP(w, r.WithContext(ctx))
      })
    }
  }

  func requestLogic(r *http.Request) {
    featureFlagEnabled := MustGetScopedClient(r.Context()).BoolVariation("example-flag-key", false)
    // use featureFlagEnabled...
  }

  ```
</CodeGroup>

To learn more, read [`GoContextWithScopedClient`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#LDClient.GoContextWithScopedClient), [`GetScopedClient`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#LDClient.GetScopedClient), and [`MustGetScopedClient`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7#LDClient.MustGetScopedClient).

## HTTPS Proxy

Go's standard HTTP library provides a built-in HTTPS proxy. If the `HTTPS_PROXY` environment variable is present, then the SDK will proxy all network requests through the URL provided.

Here is an example:

<CodeGroup>
  ```bash title="Console" lines wrap theme={null}
  export HTTPS_PROXY=https://web-proxy.domain.com:8080
  ```

  ```text title="cmd" lines wrap theme={null}
  set HTTPS_PROXY=https://web-proxy.domain.com:8080
  ```
</CodeGroup>

You can also specify a proxy programmatically through the SDK configuration:

<CodeGroup>
  ```go title="Go SDK" lines wrap theme={null}
  var config ld.Config
  config.HTTP = ldcomponents.HTTPConfiguration().
      ProxyURL("https://web-proxy.domain.com:8080")
  ```
</CodeGroup>

## Shut down the client

Shut down the client when your application terminates. To learn more, read [Shutting down](/docs/sdk/features/shutdown#go).

## Supported features

This SDK supports the following features:

* [SDK configuration](/docs/sdk/features/config#go), including
  * [Application metadata configuration](/docs/sdk/features/app-config#go)
  * [Migration configuration](/docs/sdk/features/migration-config#go)
  * [Service endpoint configuration](/docs/sdk/features/service-endpoint-configuration#go)
* [Anonymous contexts and users](/docs/sdk/features/anonymous#go)
* [Big segments](/docs/sdk/features/big-segments#go)
* [Context configuration](/docs/sdk/features/context-config#go)
* [Data saving mode](/docs/sdk/features/data-saving-mode#go)
* [Flag variation evaluation](/docs/sdk/features/evaluating#go)
* [Flag variation evaluation details](/docs/sdk/features/evaluation-reasons#go)
* [Flushing events](/docs/sdk/features/flush#go)
* [Getting all flags](/docs/sdk/features/all-flags#go)
* [Hooks](/docs/sdk/features/hooks#go)
* [Identifying and changing contexts](/docs/sdk/features/identify#go)
* [Logging configuration](/docs/sdk/features/logging#go)
* [Migrations](/docs/sdk/features/migrations#go)
* [Monitoring SDK status](/docs/sdk/features/monitoring#go)
* [Observability](/docs/sdk/observability/go)
* [Offline mode](/docs/sdk/features/offline-mode#go)
* [OpenTelemetry](/docs/sdk/features/opentelemetry-server-side#go)
* [Private attributes](/docs/sdk/features/private-attributes#go)
* [Reading flags from a file](/docs/sdk/features/flags-from-files#go)
* [Relay Proxy configuration](/docs/sdk/features/relay-proxy-configuration)
  * [Using proxy mode](/docs/sdk/features/relay-proxy-configuration/proxy-mode#go)
  * [Using daemon mode](/docs/sdk/features/relay-proxy-configuration/daemon-mode#go)
* [Secure mode](/docs/sdk/features/secure-mode#go)
* [Tracking custom events](/docs/sdk/features/events#go)
* [Shutting down](/docs/sdk/features/shutdown#go)
* [Storing data](/docs/sdk/features/storing-data#go)
* [Subscribing to flag changes](/docs/sdk/features/flag-changes#go)
* [Test data sources](/docs/sdk/features/test-data-sources#go)
* [Web proxy configuration](/docs/sdk/features/web-proxy#go)
