• HOME
  • INTEGRATIONS
  • SDKS
  • GUIDES
  • API DOCS
No results for ""
EXPAND ALL
CLOSE
launchdarkly.com

EDIT ON GITHUB

Go SDK reference

Read time: 7 minutes
Last edited: Sep 19, 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.

Go version compatibility
Version 5.0 and higher of the LaunchDarkly Go SDK is compatible with Go 1.14 and higher.

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. How you do this depends on what dependency management system you are using:

  • For the standard Go modules system, you can simply import the SDK packages in your code and go build will automatically download them. The SDK and its dependencies are modules.
  • If you are using dep, import the SDK packages in your code and run dep ensure.
  • Or you can use the go get command (for instance, go get gopkg.in/launchdarkly/go-server-sdk.v5).

There are several packages that you can import, depending on which features you are using. You will usually need the following:

1import (
2 // go-sdk-common.v2/lduser defines LaunchDarkly's model for user properties
3 "gopkg.in/launchdarkly/go-sdk-common.v2/lduser"
4
5 // go-server-sdk.v5 is the main SDK package - here we are aliasing it to "ld"
6 ld "gopkg.in/launchdarkly/go-server-sdk.v5"
7
8 // go-server-sdk.v5/ldcomponents is for advanced configuration options
9 "gopkg.in/launchdarkly/go-server-sdk.v5/ldcomponents"
10)

It is usually a good practice to pin your dependencies to a specific version. Refer to the SDK releases page to identify the latest version. Whenever you update your version of go-server-sdk, you should also update go-sdk-common.

Once the SDK is installed and imported, you'll want to create a single, shared instance of the LaunchDarkly client (LDClient). You must 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, as shown above.

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

The second argument to MakeClient is a timeout parameter: in this case, you are telling the SDK that it can spend up to 5 seconds attempting to connect to LaunchDarkly services before returning to your application. See MakeClient for more details about what the timeout means and what happens if initialization fails.

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 the LDClient methods, you can check which variation a particular user should receive for a given feature flag. See Variation and VariationDetail below for more details. See Users for more about how user properties are specified-- in this example, there is a user key that consists of an email address.

1import (
2 "gopkg.in/launchdarkly/go-sdk-common.v2/lduser"
3)
4
5flagKey := "some-flag-key"
6user := lduser.NewUser("some-user-key")
7showFeature, _ := ldClient.BoolVariation(flagKey, user, false)
8if showFeature {
9 // application code to show the feature
10} else {
11 // the code to run if the feature is off
12}

Lastly, when your application is about to terminate, shut down the LDClient with Close(). 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
2ldClient.Close()

Customizing your client

You can also pass custom parameters to the client by creating a custom configuration object.

1import (
2 ld "gopkg.in/launchdarkly/go-server-sdk.v5"
3 "gopkg.in/launchdarkly/go-server-sdk.v5/ldcomponents"
4)
5
6var config ld.Config
7
8config.Events = ldcomponents.SendEvents().FlushInterval(10 * time.Second)
9
10ldClient := ld.MakeCustomClient("YOUR_SDK_KEY", config, 5 * time.Second)

Here, we've customized the event flush interval parameter. For more about the configuration options, see Config.

Users

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

1import (
2 "gopkg.in/launchdarkly/go-sdk-common.v2/lduser"
3 "gopkg.in/launchdarkly/go-sdk-common.v2/ldvalue" // for custom attributes - see below
4)
5
6// User with only a key
7user1 := lduser.NewUser("user1-key")
8
9// User with a key plus other attributes
10user2 := lduser.NewUserBuilder("user2-key").
11 FirstName("Ernestina").
12 LastName("Events").
13 Email("ernestina@example.com").
14 Custom("groups", ldvalue.ArrayOf(
15 ldvalue.String("Google"), ldvalue.String("Microsoft"))).
16 Build()

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:

  • You can set the configuration option 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.
  • You can set the configuration option PrivateAttributeNames to a list of attribute names. 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.
1import (
2 ld "gopkg.in/launchdarkly/go-server-sdk.v5"
3 "gopkg.in/launchdarkly/go-server-sdk.v5/ldcomponents"
4)
5
6var config ld.Config
7
8// Make all attributes private for all users
9config.Events = ldcomponents.SendEvents().AllAttributesPrivate(true)
10
11// Or, make just the name and email attributes private for all users
12config.Events = ldcomponents.SendEvents().
13 PrivateAttributeNames(lduser.NameAttribute, lduser.EmailAttribute)

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

1import (
2 "gopkg.in/launchdarkly/go-sdk-common.v2/lduser"
3)
4
5user := lduser.NewUserBuilder("user-key").
6 FirstName("Ernestina").
7 LastName("Events").
8 Email("ernestina@example.com").AsPrivateAttribute().
9 Build()

Anonymous users

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

1import (
2 "gopkg.in/launchdarkly/go-sdk-common.v2/lduser"
3)
4
5// Anonymous user with only a key
6user1 := lduser.NewAnonymousUser("user1-key")
7
8// Anonymous user with a key plus other attributes
9user2 := lduser.NewUserBuilder("user2-key").
10 Anonymous(true).
11 Country("US").
12 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!

Variation

The Variation methods determine whether a flag is enabled or not for a specific user. In Go, there is a Variation method for each type: BoolVariation, IntVariation, Float64Variation, StringVariation (and JSONVariation, which can be any JSON type):

1result, _ := ldClient.BoolVariation("your.feature.key", user, false)
2
3// result is now true or false depending on the setting of this boolean feature flag

Variation methods 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. In the example above the default value is false.

The Variation call generates analytics events to tell LaunchDarkly about the flag evaluation and the user properties, so the user will be created in LaunchDarkly if a user with that 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).

VariationDetail

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.

Track

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, using TrackEvent to send an event called completed-purchase (which might correspond to a goal with the same key). Note that some of the methods have different names in earlier versions of the SDK.

1ldClient.TrackEvent("completed-purchase", user)

You can also attach custom data to your event by calling TrackData, which takes an extra parameter:

1import (
2 "gopkg.in/launchdarkly/go-sdk-common.v2/ldvalue"
3)
4
5data := ldvalue.BuildObject().Set("price", ldvalue.Int(320)).Build()
6ldClient.TrackData("completed-purchase", user, data)

Or, if you are using experimentation, you can specify a numeric metric with TrackMetric:

1import (
2 "gopkg.in/launchdarkly/go-sdk-common.v2/ldvalue"
3)
4
5metricValue := 2.5
6noOtherData := ldvalue.Null()
7ldClient.TrackMetric("page-load-time", user, metricValue, noOtherData)

Identify

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 the Variation methods automatically creates users on the dashboard for you. Identify can be useful if you want to pre-populate your dashboard before launching any features.

1ldClient.Identify(user)

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.

In this example, an extra ClientSideOnly option is specified so that only the feature flags designated for client-side use will be included in the result.

1import (
2 "gopkg.in/launchdarkly/go-server-sdk.v5/interfaces/flagstate"
3)
4
5state := ldClient.AllFlagsState(user, flagstate.OptionClientSideOnly())

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.

1ldClient.SecureModeHash(user)

Flush

Internally, the LaunchDarkly SDK keeps an event buffer for the analytics events that are produced by calling the ...Variation or ...VariationDetail methods, the Track... methods, or Identify. These are flushed periodically in a background thread. In some situations, you may want to manually call Flush to process events immediately.

1ldClient.Flush();

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

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

Logging

The Go SDK uses a logging abstraction that can write to a log.Logger (or anything with a compatible interface), but adds a system of log levels (Debug, Info, Warn, and Error) similar to logging frameworks on other platforms. By default, all levels of messages are enabled except Debug. You can tell the SDK to enable more or fewer levels, to send the output to a different destination, or to disable logging.

1import (
2 "log"
3 "os"
4 ldlog "gopkg.in/launchdarkly/go-sdk-common.v2"
5 ld "gopkg.in/launchdarkly/go-server-sdk.v5"
6 "gopkg.in/launchdarkly/go-server-sdk.v5/ldcomponents"
7)
8
9var config ld.Config
10
11// Send output to a file, and change minimum level to Warn (so Debug and Info are disabled)
12file, _ := os.Create("app.log")
13config.Logging = ldcomponents.Logging().
14 BaseLogger(log.New(file, "", log.LstdFlags)).
15 MinLevel(ldlog.Warn)
16
17// Or, disable logging
18config.Logging = ldcomponents.NoLogging()

Be aware of two considerations if you enable 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.

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.

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

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

1import (
2 ld "gopkg.in/launchdarkly/go-server-sdk.v5"
3 "gopkg.in/launchdarkly/go-server-sdk.v5/ldcomponents"
4)
5
6var config ld.Config
7config.HTTP = ldcomponents.HTTPConfiguration().
8 ProxyURL("https://web-proxy.domain.com:8080")