Feature Library for Go

Typed feature flags for Go, with targeted rollouts, live updates, and consistent request snapshots.
Quick Start · Drivers · Examples · API
Features
| Feature | What you get |
|---|---|
| Boolean, string, integer, float, and object values with explicit fallbacks and ordered rules. | |
| Stable percentages, named variants, weighted splits, and scheduled or progressive rules. | |
| One captured revision for every decision in a request or job. | |
| Publish complete valid documents; retain the last valid snapshot after failures. |
Quick start
Enable the new checkout for pro tenants.
// Keep this flag local to the process for the demo.
ctx := context.Background()
document := feature.Document{
Schema: feature.TypedSchemaVersion,
Flags: map[string]feature.Flag{
"checkout-v2": {
Default: false,
Rules: []feature.Rule{
{Attributes: map[string]string{"plan": "pro"}, Value: true},
},
},
},
}
source, err := feature.NewMemorySource(document)
if err != nil {
panic(err)
}
engine, err := feature.Open(ctx, source)
if err != nil {
panic(err)
}
// Evaluate checkout for one tenant and plan.
target := feature.Target{
Key: "tenant:acme",
Attributes: map[string]any{"plan": "pro"},
}
features := feature.New(engine)
flags := features.For(target)
fmt.Println("New checkout:", flags.Enabled(ctx, "checkout-v2"))
// New checkout: trueRead typed settings
Continue with the same scope. Every typed read takes an explicit fallback.
// Add typed settings to the same document and load the updated revision.
document.Flags["theme"] = feature.Flag{Default: "midnight"}
document.Flags["page-size"] = feature.Flag{Default: 50}
document.Flags["sample-rate"] = feature.Flag{Default: 0.25}
document.Flags["layout"] = feature.Flag{Default: map[string]any{"columns": 3}}
if err := source.Replace(document); err != nil {
panic(err)
}
if err := engine.Refresh(ctx); err != nil {
panic(err)
}
fmt.Println("Theme:", flags.String(ctx, "theme", "classic").Value)
// Theme: midnight
fmt.Println("Page size:", flags.Int(ctx, "page-size", 25).Value)
// Page size: 50
fmt.Println("Sample rate:", flags.Float(ctx, "sample-rate", 0).Value)
// Sample rate: 0.25
type layoutConfig struct {
Columns int `json:"columns"`
}
layout := feature.ObjectAs(ctx, flags, "layout", layoutConfig{Columns: 1})
fmt.Println("Columns:", layout.Value.Columns)
// Columns: 3Keep one revision for a request
Change the theme in the same process. New decisions adopt the update. A captured request keeps its original revision.
snapshot, err := features.Snapshot()
if err != nil {
panic(err)
}
request := snapshot.For(target)
document.Flags["theme"] = feature.Flag{Default: "sunrise"}
if err := source.Replace(document); err != nil {
panic(err)
}
if err := engine.Refresh(ctx); err != nil {
panic(err)
}
fmt.Println("Live theme:", flags.String(ctx, "theme", "classic").Value)
// Live theme: sunrise
fmt.Println("Captured request theme:", request.String(ctx, "theme", "classic").Value)
// Captured request theme: midnightApplication services use Features and Scope. Keep the native engine at startup for Refresh, Run, and Status. Features.Snapshot retains observer and tracking configuration; SDK drivers without genuine snapshots return ErrUnsupported.
Use a file or HTTP source with the same engine to load external definitions. Refresh explicitly or run a caller-owned polling loop. The refresh and polling examples show both workflows.
The root package requires Go 1.24 or newer and has no external runtime dependencies. The complete example catalog includes optional SDK drivers and uses Go 1.26 or newer. Install the root module:
go get github.com/goforj/featureOptional SDK modules are independently versioned:
go get github.com/goforj/feature/driver/launchdarklyfeature
go get github.com/goforj/feature/driver/openfeaturefeatureThe complete program includes the imports and setup.
Available sources
Native sources are included in the root module:
| Source | Scope | Updates |
|---|---|---|
| MemorySource | One process, no persistence | Replace the document, then refresh clients. |
| FileSource | A regular local JSON file or symlink | Read the path on refresh, including atomic file replacement. |
| HTTPSource | An explicit HTTP endpoint | Bounded complete-document retrieval with caller-owned refresh. |
| SourceFunc | Storage services or another configuration model | Application-owned complete-document retrieval and conversion. |
Native documents hold shared flag policies and bounded targeting exceptions, not a record of every user's settings. Supply user attributes at evaluation time; keep individual preferences in application-owned storage.
Source configuration is explicit. The library does not read or modify .env, start a global client, or require a flag-management service. See the versioned JSON contract for targeting rules, limits, failure behavior, and multi-process consistency.
SDK drivers
The optional adapters keep vendor dependencies and Go requirements outside the root module:
| Driver | Constructors | Minimum Go | Verification |
|---|---|---|---|
| LaunchDarkly | New borrows an SDK client; Open owns initialization and shutdown. | 1.25 | Official Relay Docker container, streaming, analytics forwarding, authentication, and outage recovery. |
| OpenFeature | New borrows a client; Open owns an isolated API and provider. | 1.26 | GO Feature Flag Docker service in remote and in-process modes; LaunchDarkly provider through its official Relay container. |
Every runtime module requires exact 100% unit statement coverage. The separate integration suite checks real services and SDK transports with race detection; its execution report identifies tested versions and source. See the capability matrix for value types, integer precision, provider differences, and current implementation boundaries. Hosted LaunchDarkly account verification remains pending. Features is the portable application API; native Client retains source refresh and genuine snapshots.
Runnable examples
Run from the repository root:
go -C examples run ./quickstart # Typed flags, tenant targeting, live updates, and snapshots.
go -C examples run ./portable # Portable checks and typed request targeting.
go -C examples run ./typed # Typed flags, application structs, arrays, and fallbacks.
go -C examples run ./validation # Definition paths and safe authoring diagnostics.
go -C examples run ./rules # Typed targeting, variants, weighted splits, and timed rollouts.
go -C examples run ./events # Observability, tracking, and change subscriptions.
go -C examples run ./http # HTTP configuration and webhook delivery.
go -C examples run ./native-provider # Native engine through an ordinary OpenFeature SDK.
go -C examples run ./targeting # Attributes and stable percentage rollout.
go -C examples run ./refresh # File replacement and request snapshots.
go -C examples run ./polling # Owned, cancellable refresh loop.
go -C examples run ./launchdarkly # Borrowed and owned SDK adapters, offline data.
go -C examples run ./openfeature # Borrowed and owned SDKs, memory provider.Tests execute every listed program and verify its output. Browse the complete examples, including application structs and arrays, definition validation, variants, splits, and timed rollouts, and the quick start.
The portable example shows the application-facing Features API. Native Client retains explicit source refresh and snapshot operations; Features borrows any Evaluator and provides short checks and owned targeting scopes.
How it works
- Local decisions: the native evaluator reads local snapshots. Optional observers and SDK providers follow their configured I/O policy. Rules match in order; otherwise the configured default applies.
- Explicit fallback: missing flags, invalid inputs, or canceled evaluations use the caller's fallback. Evaluate explains the result.
- Complete publication: refresh validates a full document before publishing one immutable revision.
- Failure retention: refresh failures retain the previous revision. Initial load failures prevent construction.
- Process boundaries: each process refreshes independently. Shared documents provide eventual convergence, with no fleet-wide atomic switch.
API index
| Group | Functions |
|---|---|
| Portable evaluation | New · Features.For · Features.Enabled · Scope.Evaluate |
| Typed evaluation | Features.String · Features.Int · Features.Float · Features.Object · ObjectAs |
| Definitions | Validate |
| Native rules | WithClock |
| Observability | WithEventSink · WithObserver · Features.SupportsTracking · Features.Track · Scope.Track |
| Changes | Subscribe |
| HTTP | NewHTTPSource · NewHTTPExporter · WithNotifier |
| LaunchDarkly | launchdarklyfeature.New · launchdarklyfeature.Open |
| OpenFeature | openfeaturefeature.Open · openfeaturefeature.New · openfeaturefeature.NewProvider |
| Construction | NewMemorySource · Open |
| Native compatibility | Enabled · Evaluate |
| Consistency | Features.Snapshot |
| Sources | Decode · NewFileSource |
| Refresh | Replace · Refresh · Run |
| Inspection | Status |
Portable evaluation
New · Features.For · Features.Enabled · Scope.Evaluate
New wraps an initialized evaluator without I/O, global registration, or workers.
For owns a target for repeated checks without mutating a shared client. Invalid targets are retained as a classified error for subsequent evaluations. A Scope captures targeting data, not a provider configuration snapshot.
Enabled evaluates an untargeted flag with a false fallback.
Evaluate explains a targeted flag with an explicit fallback.
features := feature.New(engine)
checkout := features.For(feature.Target{
Key: "tenant:acme",
Kind: "organization",
Attributes: map[string]any{"plan": "pro", "paid": true},
})
fmt.Println("Tenant checkout:", checkout.Enabled(ctx, "checkout-v2"))
// Tenant checkout: true
fmt.Println("Untargeted checkout:", features.Enabled(ctx, "checkout-v2"))
// Untargeted checkout: false
decision := checkout.Evaluate(ctx, "unknown-feature", true)
fmt.Println("Explicit fallback:", decision.Value, decision.Reason)
// Explicit fallback: true missingTyped evaluation
Features.String · Features.Int · Features.Float · Features.Object
String returns a typed decision with an explicit fallback.
Int returns a typed decision with an explicit fallback.
Float returns a typed decision with an explicit fallback.
Object returns a typed decision with an explicit fallback.
fmt.Println("Theme:", flags.String(ctx, "theme", "classic").Value)
// Theme: classic
fmt.Println("Page size:", flags.Int(ctx, "page-size", 10).Value)
// Page size: 25
fmt.Println("Sample rate:", flags.Float(ctx, "sample-rate", 0).Value)
// Sample rate: 0.25
layout := flags.Object(ctx, "layout", map[string]any{"columns": 1})
fmt.Println("Columns:", layout.Value.(map[string]any)["columns"])
// Columns: 2
fmt.Println("Menu:", flags.Object(ctx, "menu", []any{}).Value)
// Menu: [home billing]ObjectAs
ObjectAs decodes an object or array flag into an application type using JSON tags. It preserves decision metadata and returns an owned fallback on resolution or decoding failure. Decoding errors are ErrInvalidValue, without field names or source contents. Fallbacks must encode as bounded JSON objects or arrays; unknown fields are ignored. Numbers in interface fields use json.Number to avoid silently rounding native integers. Concrete fields follow encoding/json conversions; use int64 or json.Number for exact integers. Results and owned fallbacks contain only their JSON-visible representation. Custom JSON marshalers and unmarshalers are application-owned code.
type layoutConfig struct {
Columns int `json:"columns"`
}
layoutResult := feature.ObjectAs(ctx, flags, "layout", layoutConfig{Columns: 1})
fmt.Println("Typed columns:", layoutResult.Value.Columns)
// Typed columns: 2
menu := feature.ObjectAs(ctx, flags.For(feature.Target{Key: "tenant:acme"}), "menu", []string{"home"})
fmt.Println("Typed menu:", menu.Value)
// Typed menu: [home billing]Definitions
Validate
Validate checks the same complete definition accepted by Open, Encode, and Replace. Invalid definitions return a ValidationError describing one identified problem. Diagnostics are deterministic and bounded, and never publish or mutate the document. Runtime source operations continue to return only ErrInvalidDocument.
document := feature.Document{
Schema: feature.TypedSchemaVersion,
Flags: map[string]feature.Flag{
"theme": {DefaultVariant: "missing"},
},
}
if err := feature.Validate(document); err != nil {
var issue *feature.ValidationError
if !errors.As(err, &issue) {
panic(err)
}
fmt.Println("Definition path:", issue.Path)
// Definition path: /flags/theme/default_variant
fmt.Println("Problem:", issue.Problem)
// Problem: default variant must reference the flag's variant catalog
fmt.Println("Runtime classification:", err)
// Runtime classification: feature: invalid document
}Native rules
WithClock
WithClock supplies evaluation time for scheduled rules and deterministic application tests. The clock must be non-nil, local, and safe for concurrent calls.
engine, err := feature.Open(ctx, source, feature.WithClock(func() time.Time { return now }))
if err != nil {
panic(err)
}
target := feature.Target{Key: "tenant:acme", Attributes: map[string]any{"paid": true, "seats": 12}}
features := feature.New(engine)
flags := features.For(target)
fmt.Println("Paid tenant theme:", flags.String(ctx, "theme", "classic").Value)
// Paid tenant theme: green
experiment := flags.String(ctx, "experiment", "blue")
fmt.Println("Weighted experiment:", experiment.Value, experiment.Variant)
// Weighted experiment: blue control
snapshot, err := features.Snapshot()
if err != nil {
panic(err)
}
request := snapshot.For(target)
now = start
fmt.Println("Scheduled launch:", flags.Enabled(ctx, "launch"))
// Scheduled launch: true
now = end
fmt.Println("Rollout at completion:", flags.Enabled(ctx, "rollout"))
// Rollout at completion: true
fmt.Println("Captured request launch:", request.Enabled(ctx, "launch"))
// Captured request launch: falseObservability
WithEventSink · WithObserver · Features.SupportsTracking · Features.Track · Scope.Track
WithEventSink attaches application-owned analytics to the native engine.
WithObserver attaches an application-owned observer without logging values or identities.
SupportsTracking reports configured tracking support, including native sink selection. Borrowed OpenFeature clients can report SDK submission support without proving provider delivery.
Track submits an untargeted custom event through the configured capability.
Track submits a custom event with the scope's owned request targeting.
engine, err := feature.Open(ctx, source, feature.WithEventSink(sink))
if err != nil {
panic(err)
}
flags := feature.New(engine, feature.WithObserver(feature.ObserverFunc(func(context.Context, feature.Observation) { observations++ })))
fmt.Println("Tracking configured:", flags.SupportsTracking())
// Tracking configured: true
if err := flags.Track(ctx, "checkout", feature.Event{}); err != nil {
panic(err)
}
// Tracked: checkout
if err := flags.For(feature.Target{Key: "tenant:acme"}).Track(ctx, "purchase", feature.Event{Attributes: map[string]any{"currency": "USD"}}); err != nil {
panic(err)
}
// Tracked: purchase
fmt.Println("Observed operations:", observations)
// Observed operations: 2
subscription, err := engine.Subscribe()
if err != nil {
panic(err)
}
defer subscription.Close()
<-subscription.ChangesChanges
Subscribe
Subscribe captures current health and future changes without starting a goroutine.
engine, err := feature.Open(ctx, source, feature.WithEventSink(sink))
if err != nil {
panic(err)
}
flags := feature.New(engine, feature.WithObserver(feature.ObserverFunc(func(context.Context, feature.Observation) { observations++ })))
fmt.Println("Tracking configured:", flags.SupportsTracking())
// Tracking configured: true
if err := flags.Track(ctx, "checkout", feature.Event{}); err != nil {
panic(err)
}
// Tracked: checkout
if err := flags.For(feature.Target{Key: "tenant:acme"}).Track(ctx, "purchase", feature.Event{Attributes: map[string]any{"currency": "USD"}}); err != nil {
panic(err)
}
// Tracked: purchase
fmt.Println("Observed operations:", observations)
// Observed operations: 2
subscription, err := engine.Subscribe()
if err != nil {
panic(err)
}
defer subscription.Close()
<-subscription.ChangesHTTP
NewHTTPSource · NewHTTPExporter · WithNotifier
NewHTTPSource captures explicit request policy without I/O or background workers.
NewHTTPExporter captures bounded delivery policy for analytics and change webhooks.
WithNotifier attaches a bounded, application-owned native change destination. Callbacks must not reenter this client's Refresh or Run; they may inspect Status.
source, err := feature.NewHTTPSource(feature.HTTPConfig{URL: server.URL})
if err != nil {
panic(err)
}
exporter, err := feature.NewHTTPExporter(feature.ExporterConfig{HTTP: feature.HTTPConfig{URL: server.URL}})
if err != nil {
panic(err)
}
engine, err := feature.Open(ctx, source, feature.WithNotifier(exporter), feature.WithEventSink(exporter))
if err != nil {
panic(err)
}
flags := feature.New(engine, feature.WithObserver(exporter))
fmt.Println("Remote theme:", flags.String(ctx, "theme", "classic").Value)
// Remote theme: blue
if err := flags.Track(ctx, "checkout", feature.Event{}); err != nil {
panic(err)
}
if err := exporter.LastError(); err != nil {
panic(err)
}
fmt.Println("Accepted events:", accepted.Load())
// Accepted events: 4LaunchDarkly
launchdarklyfeature.New
New borrows an initialized native client without changing its configuration or lifecycle.
borrowed := launchdarklyfeature.New(sdk)
defer borrowed.Close()
flags := feature.New(borrowed).For(feature.Target{Key: "tenant:acme"})
fmt.Println("Borrowed checkout:", flags.Enabled(ctx, "checkout-v2"))
// Borrowed checkout: truelaunchdarklyfeature.Open
Open starts the real SDK and waits for initialization without global registration. Cancellation closes a partially initialized client; successful drivers own shutdown.
owned, err := launchdarklyfeature.Open(ctx, launchdarklyfeature.Config{
SDKKey: "offline-example", SDKConfig: config,
})
if err != nil {
panic(err)
}
defer owned.Close()
checkout := feature.New(owned).For(feature.Target{Key: "tenant:acme"})
fmt.Println("Owned checkout:", checkout.Enabled(ctx, "checkout-v2"))
// Owned checkout: trueOpenFeature
openfeaturefeature.Open
Open owns an isolated API, waits for provider initialization, and starts no global binding. The SDK's isolated API is experimental and contained behind this optional module. The SDK can invoke shutdown before initialization returns when ctx is canceled. Stateful providers must synchronize those lifecycle methods. For providers without that guarantee, initialize and manage the SDK yourself and borrow it through New.
owned, err := openfeaturefeature.Open(ctx, provider)
if err != nil {
panic(err)
}
defer owned.Close()
checkout := feature.New(owned).For(feature.Target{
Key: "tenant:acme", Attributes: map[string]any{"plan": "pro", "seats": 12},
})
fmt.Println("Owned checkout:", checkout.Enabled(ctx, "checkout-v2"))
// Owned checkout: trueopenfeaturefeature.New
New borrows an initialized SDK client without changing provider bindings or lifecycle.
borrowed := openfeaturefeature.New(sdk)
defer borrowed.Close()
flags := feature.New(borrowed)
fmt.Println("Borrowed checkout:", flags.Enabled(ctx, "checkout-v2"))
// Borrowed checkout: trueopenfeaturefeature.NewProvider
NewProvider exposes an initialized engine without global registration or a second update loop. Complete SDK registration before starting the native Run loop, and serialize later registrations with Refresh: SDK initialization events can overwrite concurrent health events.
provider := openfeaturefeature.NewProvider(engine)
api := isolated.NewAPI()
defer api.Shutdown(ctx)
if err := api.SetProviderAndWait(ctx, provider); err != nil {
panic(err)
}
sdk := api.NewClient()
theme, err := sdk.StringValue(ctx, "theme", "classic", openfeature.NewTargetlessEvaluationContext(nil))
if err != nil {
panic(err)
}
fmt.Println("OpenFeature theme:", theme)
// OpenFeature theme: blueConstruction
NewMemorySource · Open
NewMemorySource validates and copies a document without starting background work.
Open loads and validates the initial document synchronously without starting workers.
// Keep this flag local to the process for the demo.
ctx := context.Background()
document := feature.Document{
Schema: feature.TypedSchemaVersion,
Flags: map[string]feature.Flag{
"checkout-v2": {
Default: false,
Rules: []feature.Rule{
{Attributes: map[string]string{"plan": "pro"}, Value: true},
},
},
},
}
source, err := feature.NewMemorySource(document)
if err != nil {
panic(err)
}
engine, err := feature.Open(ctx, source)
if err != nil {
panic(err)
}Native compatibility
Enabled
Enabled returns a local decision and counts fallback failures without recording keys.
subject := feature.Subject{Key: "tenant:acme", Attributes: map[string]string{"plan": "pro"}}
fmt.Println("Native checkout:", engine.Enabled(ctx, "checkout-v2", false, subject))
// Native checkout: trueEvaluate
Evaluate explains a decision against the latest published snapshot.
decision := engine.Evaluate(ctx, "unknown-feature", false, subject)
fmt.Println("Unknown feature:", decision.Value, decision.Reason)
// Unknown feature: false missingConsistency
Features.Snapshot
Snapshot captures native definitions and evaluation time while preserving observer and tracker policy. Capturing an existing native View is idempotent. Evaluators without native snapshot support return ErrUnsupported; a vendor SDK scope is never presented as frozen state. The returned facade borrows the same observer and tracking sink as its parent.
view, err := features.Snapshot()
if err != nil {
panic(err)
}
fmt.Println("Captured checkout:", view.Enabled(ctx, "checkout-v2"))
// Captured checkout: falseSources
Decode
Decode validates bounded strict JSON, including duplicate keys and required fields. Errors never include document text. The returned document is owned by the caller.
document, err := feature.Decode([]byte(`{
"schema": 1,
"flags": {
"checkout-v2": {
"default": false,
"rules": [{
"attributes": {"plan": "pro"},
"rollout": {"basis_points": 1000, "salt": "checkout-2026"},
"value": true
}]
}
}
}`))
if err != nil {
panic(err)
}NewFileSource
NewFileSource captures a path without accessing the filesystem. Use a stable absolute path when application code may change its working directory.
engine, err := feature.Open(ctx, feature.NewFileSource(path))
if err != nil {
panic(err)
}
features := feature.New(engine)Refresh
Replace
Replace validates a complete replacement without changing any client's snapshot. Clients adopt the new document on their next successful refresh.
if err := source.Replace(feature.Document{
Schema: feature.SchemaVersion,
Flags: map[string]feature.Flag{"checkout-v2": {Default: true}},
}); err != nil {
panic(err)
}
// Existing clients adopt replacements on their next refresh.Refresh
Refresh serializes loads and atomically publishes only complete valid documents. Source failures are redacted; context errors and document errors stay classified.
next := path + ".next"
if err := os.WriteFile(next, []byte(`{"schema":1,"flags":{"checkout-v2":{"default":true}}}`), 0600); err != nil {
panic(err)
}
if err := os.Rename(next, path); err != nil {
panic(err)
}
if err := engine.Refresh(ctx); err != nil {
panic(err)
}
fmt.Println("Current checkout:", features.Enabled(ctx, "checkout-v2"))
// Current checkout: true
fmt.Println("Captured checkout:", view.Enabled(ctx, "checkout-v2"))
// Captured checkout: falseRun
Run refreshes on ticks until cancellation, retaining valid state after load errors. The caller owns the goroutine and must wait for Run to return during shutdown.
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
done := make(chan error, 1)
go func() { done <- engine.Run(runCtx, 20*time.Millisecond) }()Inspection
Status
Status returns a detached freshness record; view evaluations are intentionally uncounted.
status := engine.Status()
fmt.Println("Refresh healthy:", status.LastError == nil && !status.LastSuccess.IsZero())
// Refresh healthy: trueDevelopment
make test-unit # Execute tests and examples; require exact library coverage.
make test-race # Include race instrumentation in executable examples.
make test-integration # Require Docker; test real services and SDK transports.
make vet
make record-unit # Refresh tracked evidence after relevant source changes.
make generate
make check-generatedSee development for module ownership, validation commands, and publication status. Framework integration, hosted providers, and administration interfaces are separate from this standalone library.
The remaining-work checklist tracks library review, real-App validation, GoForj integration, and release preparation. The provider study records the design research; both initial SDK adapters and their local service integration suites are implemented.