Go SDK Reference
This topic explains how to integrate your feature flags with Go SDK.
This topic describes how to use the Harness Feature Flags Go SDK for your Go application.
For getting started quickly, you can use our sample code from the SDK README. You can also clone and run a sample application from the Go SDK GitHub Repository.
Before you begin
Make sure you read and understand:
Version
Latest SDK version can be found on GitHub Release Page
Requirements
To use this SDK, make sure you:
Starting with SDK version v0.1.21, Golang version 1.20 or later is required.
Earlier versions of the SDK require Golang versions newer than 1.6 but older than 1.19.
For installation details, please refer to Golang's official installation guide.
Create a Go application, or clone our sample application.
Create a Feature Flag on the Harness Platform. If you are following along with the SDK README sample code, make sure your flag is called
harnessappdemodarkmode.
Install the SDK
Install the SDK using the following Go command:
Import the SDK
Import the SDK using the following Go command:
Initialize the SDK
To initialize the Go SDK, you need to:
Add your Server SDK Key to connect to your Harness Environment.
(Optional) Configure the SDK options. For more details on what features you can configure for this SDK, go to Configure the SDK.
Complete the initialization by creating an instance of the Feature Flag client and passing in the Server SDK Key and Configuration.
Add a Target that you want to Evaluate against a Feature Flag.
Add the Server SDK Key
To connect to the correct Environment that you set up on the Harness Platform, you need to add the Server SDK Key from that Environment. Input the Server SDK Key into the sdkKey parameter. For example:
Configure the SDK
You can configure the following features of the SDK:
Name
Example
Description
Default Value
baseUrl
harness.WithURL("https://config.ff.harness.io/api/1.0")
The URL used to fetch Feature Flag Evaluations. When using the Relay Proxy, change this to: http://localhost:7000
https://config.ff.harness.io/api/1.0
eventUrl
harness.WithEventsURL("https://events.ff.harness.io/api/1.0")
The URL for posting metrics data to the Feature Flag service. When using the Relay Proxy, change this to: http://localhost:7000
https://events.ff.harness.io/api/1.0
pollInterval
harness.WithPullInterval(60))
The interval in seconds that we poll for changes when you are using stream mode.
60 (seconds)
streamEnabled
harness.WithStreamEnabled(false)
Set to true to enable streaming mode.Set to false to disable streaming mode.
true
analyticsEnabled
harness.WithAnalyticsEnabled(false)
Set to true to enable analytics.Set to false to disable analytics.Note: Analytics are not cached.
true
For further configuration options and samples, such as configuring your logger or using the SDK with the Relay Proxy, go to Additional Options.
Complete the initialization
Complete the initialization by creating an instance of the Feature Flag client and passing in the sdkKey, and any configuration options. For example:
Block initialization
By default, when initializing the Harness Feature Flags client, the initialization process is non-blocking. This means that the client creation call returns immediately, allowing your application to continue its startup process without waiting for the client to be fully initialized. If you evaluate a flag before the client has finished initializing, the default variation you provided can be returned as the evaluation result, because the SDK has not finished caching your remote Flag configuration stored in Harness.
You can choose to wait for the client to finish initializing before continuing. To achieve this, you can use the WithWaitForInitialized option, which blocks until the client is fully initialized. Example usage:
In this example, WaitForInitialized blocks for up to 5 authentication attempts. If the client is not initialized within 5 authentication attempts, it returns an error.
This can be useful if you need to unblock after a certain time.
Add a target
For more information about Targets, go to Targeting Users With Flags.
To add a Target, build it and pass in arguments for the following:
Parameter
Description
Required?
Example
Identifier
Unique ID for the Target.Read Regex requirements for Target names and identifiers below for accepted characters.
Required
Identifier: "HT_1"
Name
Name for this Target. This does not have to be unique. Note: If you don’t provide a value, the name will be the same as the identifier.Read Regex requirements for Target names and identifiers below for accepted characters.
OptionalNote: If you don't want to send a name, don't send the parameter. Sending an empty argument will cause an error.
Name: "Harness_Target_1"
Attributes
Additional data you can store for a Target, such as email addresses or location.
Optional
Attributes: &map[string]interface{}{"email":"demo@harness.io"},
For example:
Create a Target
Create a Target with the builder
If you create a Target with the builder, use Custom instead of Attributes.
Evaluate a Flag
Evaluating a Flag is when the SDK processes all Flag rules and returns the correct Variation of that Flag for the Target you provide.
If a matching Flag can’t be found, or the SDK can’t remotely fetch flags, the default value is returned. This will be indicated by:
The SDK will log an
infolevel log that the default variation was returned.Evaluation calls will return an
erroras well as the default variation that you can handle.
There are different methods for the different Variation types and for each method you need to pass in:
Identifier of the Flag you want to evaluate
The Target object you want to evaluate against
The default Variation
For example:
Evaluate a string Variation
Evaluate a boolean Variation
Evaluate a number Variation
Evaluate a JSON Variation
Test Your App is Connected to Harness
When you receive a response showing the current status of your Feature Flag, go to the Harness Platform and toggle the Flag on and off. Then, check your app to verify if the Flag Variation displayed is updated with the Variation you toggled.
Close the SDK client
In most applications, you won't need to close the SDK client.
However, you should close the SDK client if:
Your application is about to terminate. Closing the client ensures that all associated resources are released.
You have determined that you do not need to evaluate flags again in your application lifecycle.
To close the SDK client:
Assuming you have initialized an SDK client instance named
client, call the following function:
Additional options
Configure your logger
The SDK has a default logger, however, you can provide your own logger to the SDK by passing it in as a configuration option.
For example, the following creates an instance of the logrus logger and passes it in as a configuration option:
Use the Relay Proxy
When using your Feature Flag SDKs with a Harness Relay Proxy you need to change the default URL and events URL to http://localhost:7000 when initializing the SDK. For example:
Configure your HTTP Client
The SDK has a default HTTP client, however, you can provide your own HTTP client to the SDK by passing it in as a configuration option.
For example, the following creates an HTTP client using custom CAs for Harness Self-Managed Enterprise Edition (on premises).
For a full example of providing custom CAs for Harness Self-Managed Enterprise Edition, see our TLS Example
Sample code for a Go application
Here is a sample code for integrating with the Go SDK:
Troubleshooting
The SDK logs the following codes for certain lifecycle events, for example authentication, which can aid troubleshooting.
Code
Description
Log Level
1000
Successfully initialized
Info
1001
Failed to initialize due to authentication error
Error
1002
Failed to initialize due to a missing or empty API key
Error
1003
WaitForInitialization configuration option was provided and the SDK is waiting for initialization to finish
Info
2000
Successfully authenticated
Info
2001
Authentication failed with a non-recoverable error
Error
2002
Authentication failed and is retrying
Warn
2003
Authentication failed and max retries have been exceeded
Error
3000
SDK closing
Info
3001
SDK closed successfully
Info
4000
Polling service started
Info
4001
Polling service stopped
Info
5000
Streaming connected
Info
5001
Streaming disconnected
Warn
5002
Streaming event received
Debug
5003
Streaming disconnected and is retrying to connect
Info
5004
Streaming service stopped
Info
6000
Evaluation was successful
Debug
6001
Evaluation failed and the default value was returned
Info
7000
Metrics service has started
Info
7001
Metrics service has stopped
Info
7002
Metrics posting failed
Warn
7003
Metrics posting success
Debug
7004
Metrics max target size exceeded
Warn
7007
Metrics max evaluation size reached
Warn
Last updated
Was this helpful?