Skip to main content

Evaluate Flaggr feature flags from Go with Flaggr's Go SDK, or with the OpenFeature Go SDK and its OFREP provider

Last updated November 21, 2026

Go SDK

There are two ways to evaluate Flaggr flags from Go:

You can also call the REST API directly.

Installation

go get github.com/flaggr-dev/flaggr-go@latest

The module (v0.1.1) needs Go 1.22 or later and uses only the standard library; its next release, which adds the errorreport package, needs Go 1.27. The package name is flaggr. Its source and README are on GitHub, and its reference is on pkg.go.dev.

Quick Start

package main
 
import (
	"context"
	"log"
	"os"
 
	flaggr "github.com/flaggr-dev/flaggr-go"
)
 
func main() {
	client, err := flaggr.NewClient(
		flaggr.WithAPIURL("https://api.flaggr.dev"),
		flaggr.WithAPIKey(os.Getenv("FLAGGR_TOKEN")),         // project API token (fgr_...)
		flaggr.WithServiceID(os.Getenv("FLAGGR_SERVICE_ID")), // the service's ID, not its slug
		flaggr.WithEnvironment("production"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
 
	enabled, err := client.Boolean(context.Background(), "checkout-v2", false,
		flaggr.EvalContext{TargetingKey: "user-123"})
	if err != nil {
		log.Printf("checkout-v2: using the default: %v", err)
	}
	log.Printf("checkout-v2 = %v", enabled)
}

The client needs two values from your project:

  • A project API token (fgr_…). A read-only token is enough to evaluate flags. Personal access tokens (fgp_…) can't evaluate flags. See API Tokens.
  • The service's ID, from the service's Connection tab. Its slug or name won't work.

NewClient returns an error when either is empty. The options remove surrounding whitespace, such as the newline a secrets file can end with, and WithAPIURL removes trailing slashes. A Client is safe for concurrent use: create one and reuse it.

Environments

The client evaluates in production unless you pass flaggr.WithEnvironment. Each flag has its own configuration in each environment, so the same key can return different values in development, staging and production. (OFREP requests default to development instead; see below.)

API URL

flaggr.WithAPIURL("https://api.flaggr.dev") sends evaluations to Flaggr's data plane, which the TypeScript and Python SDKs use by default. Without it, the client sends them to https://flaggr.dev, the control plane. The two differ:

  • Experiments. A running experiment assigns its variants only on https://flaggr.dev. The data plane serves the flag without the experiment.
  • Recorded evaluations. Flag health and impact analysis count the evaluations https://flaggr.dev serves. The data plane records none.
  • Rate limits. https://flaggr.dev allows 1,000 evaluation requests a minute from one IP address, 5,000 per token and 10,000 per service, and answers 429 past that. See Rate Limiting.
  • Context values. https://flaggr.dev answers 400 for attribute values that aren't strings, numbers or booleans.

Evaluating Flags

Each call sends one POST /api/flags/evaluate request. The client doesn't cache results.

MethodReturns
Boolean(ctx, key, defaultValue, evalCtx...)(bool, error)
String(ctx, key, defaultValue, evalCtx...)(string, error)
Number(ctx, key, defaultValue, evalCtx...)(float64, error)
Object(ctx, key, defaultValue, evalCtx...)(map[string]interface{}, error)
Resolve(ctx, key, defaultValue, evalCtx...)(*EvaluationDetail, error): the value, reason, variant and any error code
ctx := context.Background()
user := flaggr.EvalContext{
	TargetingKey: "user-456",
	Attributes: map[string]interface{}{
		"plan":    "enterprise",
		"country": "AU",
	},
}
 
theme, err := client.String(ctx, "app-theme", "light", user)
limit, err := client.Number(ctx, "rate-limit", 100, user)
banner, err := client.Object(ctx, "banner-config", map[string]interface{}{"text": ""}, user)
 
detail, err := client.Resolve(ctx, "checkout-v2", false, user)
if err == nil {
	log.Printf("value=%v reason=%s variant=%s", detail.Value, detail.Reason, detail.Variant)
}

The evaluation context is optional; if you pass more than one, only the first is used. TargetingKey is usually the user ID: overrides and percentage rollouts use it. Attributes hold the strings, numbers and booleans your targeting rules match on.

Error Handling

The methods don't panic. When a request fails, because of a network error, the 5-second timeout or a status other than 200 (such as 401, 403 or 429), the typed methods return your default value and a non-nil error that names the status, and Resolve returns a nil detail and the error. Log the error and carry on with the default:

enabled, err := client.Boolean(ctx, "checkout-v2", false, user)
if err != nil {
	log.Printf("checkout-v2: using the default: %v", err)
}

The typed methods return your default with a nil error in two cases:

  • The flag doesn't exist in that service and environment. Resolve gives the reason: FLAG_NOT_FOUND from the data plane, NOT_FOUND from https://flaggr.dev.
  • The flag's value has another type than the method's, such as Number on a string flag. Boolean reads the string "true" as true and any other string as false.

A 401 or 403 can also mean the service ID is wrong: Flaggr answers the same for a service that doesn't exist and one the token can't read. To change the timeout or the transport, pass your own *http.Client with flaggr.WithHTTPClient.

Error Reporting

The errorreport package (github.com/flaggr-dev/flaggr-go/errorreport) sends errors and panics to Flaggr's Issues page, along with the flag variants they happened under. It needs a project API token, not an SDK key.

reporter := errorreport.New(errorreport.Options{
	Token:       os.Getenv("FLAGGR_ERRORS_TOKEN"),
	Release:     "checkout-api@2.8.1",
	Environment: "production",
})
defer reporter.Close()
defer reporter.Recover() // report a panic, then re-panic
 
http.Handle("/", reporter.Middleware(mux))
 
if err := placeOrder(ctx); err != nil {
	reporter.CaptureError(err, errorreport.WithFlags(map[string]string{"coupon-engine": variant}))
}

With TracesSampleRate set, the middleware also records requests as spans for the Performance page, continuing W3C traceparent headers. StartSpan adds child spans and Transport traces outgoing calls.

Events are grouped by the innermost frames of your own code, without line numbers. WithFingerprint picks the group yourself. SetFlag, SetTag, SetUser and AddBreadcrumb add context to later events. See the package README.

Local Evaluation

With flaggr.WithLocalEvaluation(true), Boolean and String answer from an in-process cache instead of the API. The client doesn't download flag configurations: you fill the cache with LoadFlags or SetFlag, and remove a flag with InvalidateFlag. Local evaluation applies a flag's on/off state, its default value and overrides that list the TargetingKey. It doesn't apply targeting rules or percentage rollouts, and Number, Object and Resolve still call the API. See the SDK's README.

OpenFeature (OFREP)

The OpenFeature Go SDK evaluates Flaggr flags through its OFREP provider.

Install the SDK and provider

go get github.com/open-feature/go-sdk github.com/open-feature/go-sdk-contrib/providers/ofrep

Configure the provider

package main
 
import (
	"context"
	"log"
	"os"
 
	"github.com/open-feature/go-sdk-contrib/providers/ofrep"
	"github.com/open-feature/go-sdk/openfeature"
)
 
func main() {
	provider := ofrep.NewProvider("https://api.flaggr.dev/api",
		ofrep.WithBearerToken(os.Getenv("FLAGGR_TOKEN")),
		ofrep.WithHeader("X-Service-Id", os.Getenv("FLAGGR_SERVICE_ID")),
		ofrep.WithHeader("X-Environment", "production"),
	)
	if err := openfeature.SetProviderAndWait(provider); err != nil {
		log.Fatal(err)
	}
	client := openfeature.NewClient("web-app")
	enabled, _ := client.BooleanValue(context.Background(), "checkout-v2", false,
		openfeature.NewEvaluationContext("user-123", nil))
 
	log.Printf("checkout-v2 = %v", enabled)
}

Four settings connect the provider to Flaggr:

  • Base URL https://api.flaggr.dev/api. The provider appends /ofrep/v1/evaluate/flags/{key} itself, so a base URL ending in /ofrep or /ofrep/v1 returns 404. Import the provider as github.com/open-feature/go-sdk-contrib/providers/ofrep; it has no /pkg subpackage.
  • ofrep.WithBearerToken sends the API token. Read it from the environment (FLAGGR_TOKEN here). A read-only project API token is enough to evaluate flags.
  • ofrep.WithHeader("X-Service-Id", …) names your service. Pass one WithHeader option per header.
  • ofrep.WithHeader("X-Environment", …) chooses the environment. Without it, flags evaluate in development.

Evaluate with OpenFeature

ctx := context.Background()
evalCtx := openfeature.NewEvaluationContext("user-456", map[string]any{
	"plan":    "enterprise",
	"country": "AU",
})
 
darkMode, err := client.BooleanValue(ctx, "dark-mode", false, evalCtx)
color, err := client.StringValue(ctx, "button-color", "blue", evalCtx)
limit, err := client.IntValue(ctx, "rate-limit", 100, evalCtx)
ratio, err := client.FloatValue(ctx, "sample-rate", 0.25, evalCtx)
banner, err := client.ObjectValue(ctx, "banner-config", map[string]any{"text": ""}, evalCtx)

Each evaluation is one HTTP request to Flaggr's data plane. The provider doesn't cache results.

The …ValueDetails methods return the value along with the reason, the variant and any error:

details, err := client.BooleanValueDetails(ctx, "checkout-v2", false, evalCtx)
if err != nil {
	log.Printf("using the default: %v", err)
}
log.Printf("value=%v reason=%s variant=%s error=%s",
	details.Value, details.Reason, details.Variant, details.ErrorCode)

openfeature.NewEvaluationContext takes a targeting key (usually the user ID) and the attributes your targeting rules match on. Attributes that apply to every evaluation can be set once, globally. They merge with the context passed to each call:

openfeature.SetEvaluationContext(openfeature.NewTargetlessEvaluationContext(map[string]any{
	"region": "ap-southeast-2",
}))

When the flag doesn't exist, the token is rejected or Flaggr can't be reached, the value methods return your default value together with a non-nil error. They don't panic. Use ofrep.WithTimeout to bound each request, or ofrep.WithClient to supply your own *http.Client.

REST API Direct Usage

To avoid dependencies, call the REST API with net/http:

package main
 
import (
	"bytes"
	"encoding/json"
	"log"
	"net/http"
	"os"
)
 
func main() {
	body, _ := json.Marshal(map[string]any{
		"flagKey":      "checkout-v2",
		"serviceId":    os.Getenv("FLAGGR_SERVICE_ID"),
		"environment":  "production",
		"defaultValue": false,
		"context":      map[string]any{"targetingKey": "user-123"},
	})
 
	req, _ := http.NewRequest("POST", "https://api.flaggr.dev/api/flags/evaluate", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("FLAGGR_TOKEN"))
	req.Header.Set("Content-Type", "application/json")
 
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
 
	var result struct {
		Value  any    `json:"value"`
		Reason string `json:"reason"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	log.Printf("checkout-v2 = %v (reason: %s)", result.Value, result.Reason)
}

Connect-RPC and gRPC

Flaggr's data plane also serves Connect-RPC and gRPC evaluation and streaming services. Generated Go stubs for them aren't published yet; see Protocols for the wire formats.