Go SDK reference
Read time: 8 minutes
Last edited: Jan 26, 2021
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, 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 rundep 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 properties3 "gopkg.in/launchdarkly/go-sdk-common.v2/lduser"45 // 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"78 // go-server-sdk.v5/ldcomponents is for advanced configuration options9 "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.
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.
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)45flagKey := "some-flag-key"6user := lduser.NewUser("some-user-key")7showFeature, _ := ldClient.BoolVariation(flagKey, user, false)8if showFeature {9 // application code to show the feature10} else {11 // the code to run if the feature is off12}
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 quit2ldClient.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)56var config ld.Config78config.Events = ldcomponents.SendEvents().FlushInterval(10 * time.Second)910ldClient := 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 below4)56// User with only a key7user1 := lduser.NewUser("user1-key")89// User with a key plus other attributes10user2 := 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.
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)56var config ld.Config78// Make all attributes private for all users9config.Events = ldcomponents.SendEvents().AllAttributesPrivate(true)1011// Or, make just the name and email attributes private for all users12config.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)45user := 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)45// Anonymous user with only a key6user1 := lduser.NewAnonymousUser("user1-key")78// Anonymous user with a key plus other attributes9user2 := 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!
Aliased users
There are situations in which multiple LaunchDarkly users can represent one person. For example, this can happen when a person initially logs into an application. The person might be represented by an anonymous user before they log in, and a different user after they log in. In that case, that one person would be identified by two different users as denoted by different user keys.
The SDK can associate these two LaunchDarkly users by sending an alias event. You can manually tell the SDK to send an alias event with the Alias
function.
1ldClient.Alias(newUser, previousUser)
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)23// 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)45data := 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)45metricValue := 2.56noOtherData := 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
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)45state := 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
Subscribing to feature flag changes
The SDK provides a channel-based mechanism to notify you when flag configurations change. The LDClient.GetFlagTracker()
method returns an interface for this mechanism called FlagTracker
.
Calling GetFlagTracker().AddFlagChangeListener()
provides a channel that receives a FlagChangeEvent
whenever there is a change in any feature flag's configuration, or in anything else that could indirectly affect the flag value, such as a prerequisite flag or a user segment that the flag uses. The event data consists only of the flag key. It does not contain a flag value, because in server-side SDKs, flags only have values when they are evaluated for a specific set of user properties.
1import (2 "log"3 ld "gopkg.in/launchdarkly/go-server-sdk.v5"4)56func logWheneverAnyFlagChanges(client *ld.LDClient) {7 updateCh := client.GetFlagTracker().AddFlagChangeListener()8 go func() {9 for event := range updateCh {10 log.Printf("Flag %q has changed", event.Key)11 }12 }()13}
To listen for changes in flag values for a specific flag key and user, use GetFlagTracker().AddFlagValueChangeListener()
, which provides FlagValueChangeEvent
s. This is equivalent to re-evaluating the flag for that user whenever AddFlagChangeListener()
reports a change in that flag. Because flag values can have different data types, the value is reported using the general type ldvalue.Value
.
1import (2 "log"3 ld "gopkg.in/launchdarkly/go-server-sdk.v5"4 "gopkg.in/launchdarkly/go-sdk-common.v2/lduser"5 "gopkg.in/launchdarkly/go-sdk-common.v2/ldvalue"6)78func logWheneverOneFlagChangesForOneUser(client *ld.LDClient, flagKey string, user lduser.User) {9 updateCh := client.GetFlagTracker().AddFlagValueChangeListener(flagKey, user, ldvalue.Null())10 go func() {11 for event := range updateCh {12 log.Printf("Flag %q for user %q has changed from %s to %s", event.Key,13 user.GetKey(), event.OldValue, event.NewValue)14 }15 }()16}
With both of these methods, it is the caller's responsibility to consume values from the channel. Allowing values to accumulate in the channel can cause an SDK goroutine to be blocked.
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.Config2config.Offline = true34ldClient, _ := 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)89var config ld.Config1011// 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)1617// Or, disable logging18config.Logging = ldcomponents.NoLogging()
Be aware of two considerations if you enable the Debug log level:
- Debug-level logs can be very verbose. It is not recommended that you turn on debug logging in high-volume environments.
- 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)56var config ld.Config7config.HTTP = ldcomponents.HTTPConfiguration().8 ProxyURL("https://web-proxy.domain.com:8080")