Introduction

In modern software development, feature flagging has become a powerful technique for managing the release process, improving deployment safety, and enabling continuous delivery. LaunchDarkly is a popular feature management platform that helps teams control the visibility of features in production. This article will explore how to integrate LaunchDarkly with Golang (Go), enabling you to toggle features dynamically without redeploying your application.

What is LaunchDarkly?

LaunchDarkly is a feature management and experimentation platform that enables developers to deploy code but control which users see which features. It allows teams to:

  • Gradually roll out features to users.
  • A/B test different versions of a feature.
  • Disable problematic features without a full rollback.
  • Separate code deployment from feature release.

LaunchDarkly uses feature flags (also known as feature toggles) to achieve this. Feature flags are essentially conditionals in your code that determine whether a feature is enabled for a given user or context.

How to Use LaunchDarkly

To use LaunchDarkly in your application:

  • Create a LaunchDarkly account and set up a new project and environment. https://app.launchdarkly.com/

  • Define feature flags in the LD dashboard.

  • Integrate LD SDK in your application code.

  • Evaluate feature flags at runtime and use their values to control application logic.

LaunchDarkly create feature flag


My Sample Flag -
My Sample Flag for LD


Sample Flag variations -
Sample Flag variations in LD

LaunchDarkly provides SDKs for various languages, including Go, which allow your app to interact with the LD service and evaluate flags.

Code Example with Golang

Here is a simple example of how to integrate and use LaunchDarkly in a Go application:

Step 1: Install the SDK

go get "github.com/launchdarkly/go-server-sdk/v7"

Step 2: Code Example
Here we have an example for Json Flag and also added watcher on that flag.

package main

import (
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"
    "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
    "github.com/launchdarkly/go-sdk-common/v3/ldvalue"
    ld "github.com/launchdarkly/go-server-sdk/v7"
)

// Replace with your actual LaunchDarkly SDK key
const sdkKey = "YOUR-SDK-KEY"

// Replace with the key of the JSON flag you want to evaluate
const jsonFlagKey = "json-flag"


func main() {
    // --- 1. Configure and Initialize the LaunchDarkly Client (v7) ---

    // Optional: for advanced configuration like logging
    // config := ld.Config{} // Default configuration
    // client, err := ld.MakeCustomClient(sdkKey, config, 5*time.Second)

    // Creating client with Default configuration
    client, err := ld.MakeClient(sdkKey, 5*time.Second)
    if err != nil {
        log.Fatalf("Error initializing LaunchDarkly client: %v", err)
    }
    defer func() {
        if err := client.Close(); err != nil {
            log.Printf("Error closing LaunchDarkly client: %v", err)
        }
    }()

    if !client.Initialized() {
        log.Println("Client did not initialize successfully within the timeout.")
    } else {
        log.Println("LaunchDarkly client initialized successfully.")
    }

    // --- 2. Define the Evaluation Context (v7 uses ldcontext from common v3) ---
    evaluationContext := ldcontext.New("example-context-key")
    // Add more attributes as needed:
    // evaluationContext = ldcontext.NewBuilder("example-user-key").
    //  Kind("user").
    //  Name("Example User").
    //  SetString("email", "[email protected]").
    //  Build()

    // --- 3. Read the Initial JSON Flag Value (v7 uses ldvalue from common v3) ---
    defaultValue := ldvalue.ObjectBuild().Build()
    jsonValue, err := client.JSONVariation(jsonFlagKey, evaluationContext, defaultValue)
    if err != nil {
        log.Printf("Error evaluating flag '%s': %v. Using default value.", jsonFlagKey, err)
    }
    log.Printf("Initial value for flag '%s': %s\n", jsonFlagKey, jsonValue.JSONString())

    // --- 4. Watch for Flag Changes (v7 Flag Tracker with Listener Function) ---
    WatchFlagChanges(client, jsonFlagKey, evaluationContext)

    // --- 5. Keep the Application Running ---
    log.Println("Application started. Watching for flag changes. Press Ctrl+C to exit.")

    // Wait for a termination signal (Ctrl+C)
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit

}

func WatchFlagChanges(client *ld.LDClient, flagKey string, context ldcontext.Context) {
    updateCh := client.GetFlagTracker().AddFlagValueChangeListener(flagKey, context, ldvalue.Null())
    go func() {
        for event := range updateCh {
            log.Printf("Flag %q for context %q has changed from %s to %s", event.Key,
                context.Key(), event.OldValue, event.NewValue)
        }
    }()
}

Output:

Launch Darkly Sample Output

For above output, we can see that when flag value got changed from env:stage to env:prod after I have changed the targeting for flag.

Notes:

  • Replace YOUR_SDK_KEY with your environment’s SDK key from LaunchDarkly.
  • Replace "new-feature" with the actual key of your defined flag in the LD dashboard.

Conclusion

Using LaunchDarkly with Golang allows developers to gain fine-grained control over feature rollouts and improve the deployment process. By integrating feature flags into your Go application, you can ship code with confidence, perform canary releases, and respond to production issues quickly. With just a few lines of code, LaunchDarkly enables powerful, real-time control over your application's behavior.