• SDKS
No results for ""


Go SDK reference

Read time: 6 minutes
Last edited: Jul 14, 2020

This reference guide documents all of the methods available in our Go SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, read Go SDK GitHub repository. The online Go API docs contain the programmatic definitions of every type and method. Additionally you can clone and run a sample application using this SDK.

Getting started

Building on top of our Getting Started guide guide, the following steps will get you started with using the LaunchDarkly SDK in your Go application.

The first step is to install the LaunchDarkly SDK as a dependency in your application using your application's dependency manager. Refer to the SDK releases page to identify the latest major version.

1go get gopkg.in/launchdarkly/go-server-sdk.v4

Next you should import the LaunchDarkly client in your application code.

1import ld "gopkg.in/launchdarkly/go-server-sdk.v4"

Once the SDK is installed and imported, you'll want to create a single, shared instance of the LaunchDarkly client. You should specify your SDK key here so that your application will be authorized to connect to LaunchDarkly and for your application and environment.

We'll assume you've imported the LaunchDarkly SDK package as ld:

1ldClient, _ := ld.MakeClient("YOUR_SDK_KEY", 5 * time.Second)

The timeout parameter (the second argument to MakeClient) can be used to block initialization until the client has been bootstrapped.

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.

LDClient must be a singleton

It's important to make this a singleton. The client instance maintains internal state that allows us to serve feature flags without making any remote requests. Be sure that you're not instantiating a new client with every request.

Using ldClient, you can check which variation a particular user should receive for a given feature flag.

1key := "user@test.com"
2showFeature, _ := ldClient.BoolVariation("your.flag.key", ld.NewUser(key), false)
3if showFeature {
4 // application code to show the feature
5} else {
6 // the code to run if the feature is off

Lastly, when your application is about to terminate, shut down ldClient. This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.

1// shut down the client, since we're about to quit

Customizing your client

You can also pass custom parameters to the client by creating a custom configuration object. It's easiest to create one by starting with the DefaultConfig and assigning to the fields you need to customize:

1config := ld.DefaultConfig
2config.FlushInterval = 10 * time.Second
3ldClient := ld.MakeCustomClient("YOUR_SDK_KEY", config, 5 * time.Second)

Here, we've customized the client flush interval parameter. For a complete list of configuration options for the client, read Go docs.


Feature flag targeting and rollouts are all determined by the user you pass to your Variation calls. The Go SDK defines a User struct to make this easy. Here's an example:

1// User with only a key
2user1 := ld.NewUser("user1-key")
4// User with a key plus other attributes
5user2 := ld.NewUserBuilder("user2-key").
6 FirstName("Ernestina").
7 LastName("Events").
8 Email("ernestina@example.com").
9 Custom("Ernestina", ldvalue.ArrayOf(
10 ldvalue.String("Google"), ldvalue.String("Microsoft"))).
11 Build()
13// Note that ldvalue comes from this import:
14// gopkg.in/launchdarkly/go-sdk-common.v1/ldvalue

Let's walk through this snippet. The most common attribute is the user's key. In this case we've used the strings "user1-key" and "user2-key". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other attributes (like FirstName, Email, and the Custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes. The documentation for User and UserBuilder shows all of the available attributes.

A note on types

Most of our built-in attributes (like names and e-mail addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or arrays or maps containing any of type of value supported by JSON.

In SDK versions 4.16.0 and later, these types are all represented by the ldvalue.Value type; earlier versions use the catch-all Go type interface{}.

If you enter a custom value on our dashboard that looks like a number or a boolean, it'll be interpreted that way. The Go SDK is strongly typed, so be aware of this distinction.

Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us, including organizations, groups, and account plans. Anything you pass to us becomes available instantly on our dashboard.

Private user attributes

You can optionally configure the Go SDK to treat some or all user attributes as Private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

In the Go SDK there are two ways to define private attributes for the entire LaunchDarkly client:

  • In the LaunchDarkly configuration, you can set AllAttributesPrivate to true. If this is enabled, all user attributes (except the key) for all users are removed before the user is sent to LaunchDarkly.
  • In the LaunchDarkly configuration object, you can define a list of PrivateAttributeNames. If any user has a custom or built-in attribute named in this list, it will be removed before the user is sent to LaunchDarkly.

You can also define a set of private attributes on the user object itself. In this example, Email is private for this user (in addition to any private attributes that were specified globally):

1user := ld.NewUserBuilder("user-key").
2 FirstName("Ernestina").
3 LastName("Events").
4 Email("ernestina@example.com").AsPrivateAttribute().
5 Custom("Ernestina", ldvalue.ArrayOf(
6 ldvalue.String("Google"), ldvalue.String("Microsoft"))).
7 Build()

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

1// Anonymous user with only a key
2user1 := ld.NewAnonymousUser("user1-key")
4// Anonymous user with a key plus other attributes
5user2 := ld.NewUserBuilder("user2-key").
6 Anonymous(true)
7 Country("US").
8 Build()

You will still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. You also can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. This is actually a good thing, because it keeps anonymous users from polluting your Users page!


The Variation method determines whether a flag is enabled or not for a specific user. In Go, there is a Variation method for each type (e.g. BoolVariation, StringVariation):

1shouldShow, _ := ldClient.BoolVariation("your.feature.key", user, false)

Variation calls take the feature flag key, a User, and a default value.

The default value will only be returned if an error is encountered. For example, the default value returns if the feature flag key doesn't exist or the user doesn't have a key specified.

The Variation call will automatically create a user in LaunchDarkly if a user with that user key doesn't exist already. There's no need to create users ahead of time (but if you do need to, take a look at Identify).


The VariationDetail methods (BoolVariationDetail, etc.) work the same as Variation, but also provide additional "reason" information about how a flag value was calculated (for instance, if the user matched a specific rule). You can examine the "reason" data programmatically; you can also view it with data export, if you are capturing detailed analytics events for this flag.

To learn more, read Evaluation reasons.


The Track methods allow you to record actions your users take on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. Here's a simple example:

1ldClient.TrackEvent("your-goal-key", user)

You can also attach custom data to your event by passing an extra parameter to Track:

1data := ldvalue.BuildObject().Set("price", ldvalue.Int(320)).Build()
2ldClient.TrackData("Completed purchase", user, data)


The Identify method creates or updates users on LaunchDarkly, making them available for targeting and autocomplete on the dashboard. In most cases, you won't need to call Identify. Calling Variation automatically creates users on the dashboard for you. Identify can be useful if you want to pre-populate your dashboard before launching any features.


All flags

Creating users
Note that unlike variation and identify calls, AllFlagsState does not send events to LaunchDarkly. Thus, users are not created or updated in the LaunchDarkly dashboard.",

The AllFlagsState method captures the state of all feature flag keys with regard to a specific user. This includes their values, as well as other metadata.

This method can be useful for passing feature flags to your front-end. In particular, it can be used to provide bootstrap flag settings for our JavaScript SDK.

1state := ldClient.AllFlagsState(user)


The Go SDK uses Go's built in log. All loggers are namespaced under [LaunchDarkly]. A custom logger may be passed to the SDK by the configurable Logger property:

1config := ld.DefaultConfig
2config.Logger = myLogger
3ldClient := ld.MakeCustomClient("YOUR_SDK_KEY", config, 5 * time.Second)

Secure mode hash

The SecureModeHash method computes an HMAC signature of a user signed with the client's SDK key. If you're using our JavaScript SDK for client-side flags, this method generates the signature you need for secure mode.



Internally, the LaunchDarkly SDK keeps an event buffer for track and identify calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK on the command line), you may want to manually call flush to process events immediately.


The flush interval is configurable. If you need to change the interval, you can do so by making a custom client configuration

Offline mode

In some situations, you might want to stop making remote calls to LaunchDarkly and fall back to default values for your feature flags. For example, if your software is both cloud-hosted and distributed to customers to run on premise, it might make sense to fall back to defaults when running on premise. You can do this by setting Offline mode in the client's Configuration.

1config := ld.DefaultConfig
2config.Offline = true
3ldClient, _ := ld.MakeCustomClient("YOUR_SDK_KEY", config, 5 * time.Second)
4ldClient.BoolVariation("any.feature.flag", user, false) // will always return the default value (false)


The Go SDK uses Go's built-in log package. All loggers are namespaced under [LaunchDarkly]. A custom logger may be passed to the SDK by the configurable Logger property:

1config := ld.DefaultConfig
2config.Logger = myLogger
3ldClient, _ := ld.MakeCustomClient("YOUR_SDK_KEY", config, 5 * time.Second)

Be aware of two considerations when enabling the DEBUG log level:

  1. Debug-level logs can be very verbose. It is not recommended that you turn on debug logging in high-volume environments.
  2. Potentially sensitive information is logged including LaunchDarkly users created by you in your usage of this SDK.

Database integrations

The Go SDK can use Redis, Consul, or DynamoDB as a persistent store of feature flag configurations. See Using a persistent feature store for examples.


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.

1export HTTPS_PROXY=https://web-proxy.domain.com:8080

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

1import "gopkg.in/launchdarkly/go-server-sdk.v4/ldhttp"
3config := ld.DefaultConfig
4config.HTTPClientFactory = ldhttp.NewHTTPClientFactory(
5 ldhttp.ProxyURL("https://web-proxy.domain.com:8080"))
7// This is supported only in SDK versions 4.14.0 and higher.