Go

This Backend Go SDK is designed to help you integrate with Unleash and evaluate feature flags inside your application.

You can use this client with Unleash Enterprise or Unleash Open Source.

Go Version

The client is currently tested against Go 1.21.x, 1.22.x, 1.23.x and 1.24.x. These versions will be updated as new versions of Go are released.

The client may work on older versions of Go as well, but is not actively tested.

Getting Started

1. Install unleash-go-sdk

To install the latest version of the client use:

$go get github.com/Unleash/unleash-go-sdk/v5

2. Initialize unleash

The easiest way to get started with Unleash is to initialize it early in your application code:

Asynchronous initialization example:

1import (
2 "github.com/Unleash/unleash-go-sdk/v5"
3)
4
5func init() {
6 unleash.Initialize(
7 unleash.WithListener(&unleash.DebugListener{}),
8 unleash.WithAppName("my-application"),
9 unleash.WithUrl("https://eu.app.unleash-hosted.com/demo/api/"),
10 unleash.WithCustomHeaders(http.Header{"Authorization": {"<API token>"}}),
11 )
12}

Synchronous initialization example:

1import (
2 "github.com/Unleash/unleash-go-sdk/v5"
3)
4
5func init() {
6 unleash.Initialize(
7 unleash.WithListener(&unleash.DebugListener{}),
8 unleash.WithAppName("my-application"),
9 unleash.WithUrl("https://eu.app.unleash-hosted.com/demo/api/"),
10 unleash.WithCustomHeaders(http.Header{"Authorization": {"<API token>"}}),
11 )
12
13 // Note this will block until the default client is ready
14 unleash.WaitForReady()
15}

Preloading Feature Toggles

If you’d like to prebake your application with feature toggles (maybe you’re working without persistent storage, so Unleash’s backup isn’t available), you can replace the defaultStorage implementation with a BootstrapStorage. This allows you to pass in a reader to where data in the format of /api/client/features can be found.

Bootstrapping From File

Bootstrapping from file on disk is then done using something similar to:

1import (
2 "github.com/Unleash/unleash-go-sdk/v5"
3)
4
5func init() {
6 myBootstrap := os.Open("bootstrapfile.json") // or wherever your file is located at runtime
7 // BootstrapStorage handles the case where Reader is nil
8 unleash.Initialize(
9 unleash.WithListener(&unleash.DebugListener{}),
10 unleash.WithAppName("my-application"),
11 unleash.WithUrl("https://eu.app.unleash-hosted.com/demo/api/"),
12 unleash.WithStorage(&BootstrapStorage{Reader: myBootstrap})
13 )
14}

Bootstrapping From S3

Bootstrapping from S3 is then done by downloading the file using the AWS library and then passing in a Reader to the just downloaded file:

1import (
2 "github.com/Unleash/unleash-go-sdk/v5"
3 "github.com/aws/aws-sdk-go-v2/aws"
4 "github.com/aws/aws-sdk-go-v2/config"
5 "github.com/aws/aws-sdk-go-v2/service/s3"
6)
7
8func init() {
9 // Load the shared AWS config
10 cfg, err := config.LoadDefaultConfig(context.TODO())
11 if err != nil {
12 log.Fatal(err)
13 }
14
15 // Create an S3 client
16 client := s3.NewFromConfig(cfg)
17
18 obj, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
19 Bucket: aws.String("YOURBUCKET"),
20 Key: aws.String("YOURKEY"),
21 })
22
23 if err != nil {
24 log.Fatal(err)
25 }
26
27 reader := obj.Body
28 defer reader.Close()
29
30 // BootstrapStorage handles the case where Reader is nil
31 unleash.Initialize(
32 unleash.WithListener(&unleash.DebugListener{}),
33 unleash.WithAppName("YOURAPPNAME"),
34 unleash.WithUrl("YOURINSTANCE_URL"),
35 unleash.WithStorage(&BootstrapStorage{Reader: reader})
36 )
37}

Bootstrapping From Google

Since the Google Cloud Storage API returns a Reader, implementing a Bootstrap from GCS is done using something similar to

1import (
2 "github.com/Unleash/unleash-go-sdk/v5"
3 "cloud.google.com/go/storage"
4)
5
6func init() {
7 ctx := context.Background() // Configure Google Cloud context
8 client, err := storage.NewClient(ctx) // Configure your client
9 if err != nil {
10 // TODO: Handle error.
11 }
12 defer client.Close()
13
14 // Fetch the bucket, then object and then create a reader
15 reader := client.Bucket(bucketName).Object("my-bootstrap.json").NewReader(ctx)
16
17 // BootstrapStorage handles the case where Reader is nil
18 unleash.Initialize(
19 unleash.WithListener(&unleash.DebugListener{}),
20 unleash.WithAppName("my-application"),
21 unleash.WithUrl("https://eu.app.unleash-hosted.com/demo/api/"),
22 unleash.WithStorage(&unleash.BootstrapStorage{Reader: reader})
23 )
24}

3. Use unleash

After you have initialized the unleash-client you can easily check if a feature toggle is enabled or not.

1unleash.IsEnabled("app.ToggleX")

4. Stop unleash

To shut down the client (turn off the polling) you can simply call the destroy-method. This is typically not required.

unleash.Close()

Built in Activation Strategies

The Go client comes with implementations for the built-in activation strategies provided by unleash.

  • DefaultStrategy
  • UserIdStrategy
  • FlexibleRolloutStrategy
  • GradualRolloutUserIdStrategy
  • GradualRolloutSessionIdStrategy
  • GradualRolloutRandomStrategy
  • RemoteAddressStrategy
  • ApplicationHostnameStrategy

Read more about activation strategies in the docs.

Unleash Context

In order to use some of the common activation strategies you must provide an unleash-context. This client SDK allows you to send in the unleash context as part of the isEnabled call:

1ctx := context.Context{
2 UserId: "123",
3 SessionId: "some-session-id",
4 RemoteAddress: "127.0.0.1",
5}
6
7unleash.IsEnabled("someToggle", unleash.WithContext(ctx))

Caveat

This client uses go routines to report several events and doesn’t drain the channel by default. So you need to either register a listener using WithListener or drain the channel “manually” (demonstrated in this example).

Feature Resolver

FeatureResolver is a FeatureOption used in IsEnabled via the WithResolver.

The FeatureResolver can be used to provide a feature instance in a different way than the client would normally retrieve it. This alternative resolver can be useful if you already have the feature instance and don’t want to incur the cost to retrieve it from the repository.

An example of its usage is below:

1ctx := context.Context{
2 UserId: "123",
3 SessionId: "some-session-id",
4 RemoteAddress: "127.0.0.1",
5}
6
7// the FeatureResolver function that will be passed into WithResolver
8resolver := func(featureName string) *api.Feature {
9 if featureName == "someToggle" {
10 // Feature being created in place for sake of example, but it is preferable an existing feature instance is used
11 return &api.Feature{
12 Name: "someToggle",
13 Description: "Example of someToggle",
14 Enabled: true,
15 Strategies: []api.Strategy{
16 {
17 Id: 1,
18 Name: "default",
19 },
20 },
21 CreatedAt: time.Time{},
22 Strategy: "default-strategy",
23 }
24 } else {
25 // it shouldn't reach this block because the name will match above "someToggle" for this example
26 return nil
27 }
28}
29
30// This would return true because the matched strategy is default and the feature is Enabled
31unleash.IsEnabled("someToggle", unleash.WithContext(ctx), unleash.WithResolver(resolver))

Impression Data

When impression data is enabled on a flag, the SDK will emit impression events during evaluation. You can hook into these with a custom listener to collect insights or integrate with analytics. You can read more about impression data in Unleash’s documentation.

1type MyListener struct {
2 unleash.DebugListener
3}
4
5func (l *MyListener) OnImpression(e unleash.ImpressionEvent) {
6 fmt.Printf("Custom Impression: %s = %v (%s)\n", e.FeatureName, e.Enabled, e.EventType)
7 if e.Context != nil {
8 fmt.Printf("Context: userId=%s sessionId=%s\n", e.Context.UserId, e.Context.SessionId)
9 }
10}
11
12func main() {
13 unleash.Initialize(
14 unleash.WithListener(&MyListener{}),
15 unleash.WithAppName("my-app"),
16 unleash.WithUrl("https://eu.app.unleash-hosted.com/demo/api/"),
17 )
18}

Development

To override dependency on unleash-go-sdk github repository to a local development folder (for instance when building a local test-app for the SDK), you can add the following to your apps go.mod:

1 replace github.com/Unleash/unleash-go-sdk/v5 => ../unleash-go-sdk/

Steps to Release

  • Update the clientVersion in client.go
  • Tag the repository with the new tag
  • Create the release manually in Github

Adding Client Specifications

In order to make sure the unleash clients uphold their contract, we have defined a set of client specifications that define this contract. These are used to make sure that each unleash client at any time adhere to the contract, and define a set of functionality that is core to unleash. You can view the client specifications here.

In order to make the tests run please do the following steps.

// in repository root
// testdata is gitignored
mkdir testdata
cd testdata
git clone https://github.com/Unleash/client-specification.git

Requirements:

  • make
  • golint (go get -u golang.org/x/lint/golint)

Run tests:

make

Run lint check:

make lint

Run code-style checks:(currently failing)

make strict-check

Run race-tests:

make test-race

Benchmarking

You can benchmark feature toggle evaluation by running:

go test -run=^$ -bench=BenchmarkFeatureToggleEvaluation -benchtime=10s

Here’s an example of how the output could look like:

goos: darwin
goarch: arm64
pkg: github.com/Unleash/unleash-go-sdk/v5
BenchmarkFeatureToggleEvaluation-8 Final Estimated Operations Per Day: 101.131 billion (1.011315e+11)
13635154 854.3 ns/op
PASS
ok github.com/Unleash/unleash-go-sdk/v5 13.388s

In this example the benchmark was run on a MacBook Pro (M1 Pro, 2021) with 16GB RAM.

We can see a result of 854.3 ns/op, which means around 101.131 billion feature toggle evaluations per day.

Note: The benchmark is run with a single CPU core, no parallelism.

Design Philosophy

This feature flag SDK is designed according to our design philosophy. You can read more about that here.