Docs/Ecosystem/Flags: Typed Go Feature Flags

Flags: Typed Go Feature Flags

Compile-time-typed Go feature flags with scoped overrides, deterministic percentage rollouts, request memoization, route gates, and Nock persistence.

github.com/fletchhq/flags

flagspkg.go.dev

Updated 2026-12-06 fletch docs show flags/flags 8 min read

On this page

Flags gives Go and Fletch applications compile-time-typed feature flags with scoped overrides, deterministic percentage rollouts, weighted variants, per-request memoization, and HTTP route gates.

Introduction

Feature flags built on untyped string maps and ad-hoc config checks drift quickly. A typo in a flag name silently evaluates to false, a boolean gets read as a string, and repeated checks inside one request hit the database over and over.

github.com/fletchhq/flags replaces untyped lookups with registered Flag[V] handles (BoolFlag for booleans). You define a flag once with its Go type and default Resolver[V], evaluate it for any Scope (global, user, team, or custom), and persist overrides in memory or in SQLite and Postgres via flags/nock.

Installation

Add the module to your project:

go get github.com/fletchhq/flags@v0.1.0

The root package github.com/fletchhq/flags and github.com/fletchhq/flags/flagstest depend only on the Go standard library (CGO_ENABLED=0). Database persistence lives in the github.com/fletchhq/flags/nock sub-package inside the same module, so Go compiles Nock support only when you import it.

import (
	"github.com/fletchhq/flags"
	flagsnock "github.com/fletchhq/flags/nock"
)

When github.com/fletchhq/flags is in your go.mod, fletch ax sync and fletch docs index its embedded documentation and skill automatically.

Core concepts

Defining typed flags

Create a *flags.Manager with a flags.Store, then register each flag with flags.Define[V], flags.DefineBool, or the boolean shorthand mgr.Define. Registration panics if a flag name is empty, "*", already registered, or has a nil resolver.

mgr := flags.NewManager(flags.NewMemStore())

billingV2 := flags.DefineBool(mgr, "billing_v2", flags.Rollout(25))
theme := flags.Define(mgr, "theme", flags.RolloutVariants(
	flags.Variant[string]{Value: "light", Weight: 50},
	flags.Variant[string]{Value: "dark", Weight: 50},
))

Each returned Flag[V] handle exposes Name(), Value(ctx, scope), Active(ctx, scope), Set(ctx, scope, v), and Forget(ctx, scope). For boolean flags, Active returns the boolean directly; for any other type, Active returns true when the resolved value is non-zero.

When a tool or test discovers a flag's type at runtime rather than compile time, use flags.DefineLike(mgr, name, sample) to register a zero-value resolver matching sample's type if the name is not yet defined.

Resolvers and sticky evaluation

A flags.Resolver[V] has the signature func(ctx context.Context, scope flags.Scope) (V, error). When a (flag, scope) pair has no stored value, Manager calls the resolver, JSON-encodes the result, and persists it in the Store. Subsequent reads for that scope return the stored value until you call Forget or Purge, keeping user experiences sticky across requests and deploys.

Inside a custom resolver, call flags.FlagName(ctx) to read the name of the flag being evaluated. Three built-in resolvers cover the common rollout cases:

  • flags.Const[V](v): always returns v.
  • flags.Rollout(pct): deterministic percentage rollout using FNV-1a over flag:scopeKey modulo 10000. Raising pct never turns off a previously included scope. Values <= 0 match nobody; values >= 100 match everyone.
  • flags.RolloutVariants[V](variants...): deterministic weighted assignment across flags.Variant[V]{Value, Weight} entries. Non-positive weights are skipped; if no positive weights exist, the zero V is returned.

Evaluation scopes

A flags.Scope is any type implementing ScopeKey() string. Passing nil evaluates against flags.Global.

  • flags.Global: application-wide scope ("global").
  • flags.Everyone: global override scope ("*"). Values set on Everyone win over per-scope values and resolvers.
  • flags.UserScope(id) and flags.UserIDScope(id int64): user scopes ("user:<id>").
  • flags.TeamScope(id): team scope ("team:<id>").
  • flags.StringScope(kind, id): arbitrary "<kind>:<id>" scope, such as flags.StringScope("org", orgID).

Resolution checks Everyone first, then the requested scope, and finally runs the flag's resolver if neither is stored.

Per-request memoization

Wrap your HTTP handler with flags.MemoizeMiddleware, or attach a cache manually in background jobs with flags.WithRequestCache(ctx). Every repeated read of the same (flag, scope) pair inside that context returns the memoized value without hitting the Store again.

Any mutation through the manager (Set, SetForEveryone, Activate, Deactivate, Forget, Purge, or FlushCache) invalidates the affected entries in that context's cache automatically, so a write inside a request is immediately visible to later checks in the same request.

Common tasks

Evaluating and mutating flags

Use typed handles when you hold the Flag[V] variable, or call Manager methods and the generic flags.Value[V] helper when addressing flags by name:

enabled, err := billingV2.Active(ctx, flags.UserScope(user.ID))
if err != nil {
	return err
}

currentTheme, err := flags.Value[string](ctx, mgr, "theme", flags.UserScope(user.ID))
if err != nil {
	return err
}

// Override for one user, then clear back to the resolver
_ = billingV2.Set(ctx, flags.UserScope(user.ID), true)
_ = billingV2.Forget(ctx, flags.UserScope(user.ID))

// Override globally for all scopes
_ = mgr.SetForEveryone(ctx, "billing_v2", true)

Asking flags.Value[V] for the wrong type returns flags.ErrTypeMismatch. Addressing an unregistered flag returns flags.ErrUnknownFlag unless you construct the manager with flags.WithAllowUnknown() (which makes Active return false and Set/Forget act as no-ops for unknown names, while Value[V] still returns ErrUnknownFlag).

When one request checks multiple flags for the same user or team, bind the scope once with mgr.For(scope):

scoped := mgr.For(flags.UserScope(user.ID))

on, err := scoped.Active(ctx, "billing_v2")
activeNames, err := scoped.AllActive(ctx)
variant, err := flags.ScopedValue[string](ctx, scoped, "theme")

Scoped also exposes Set, Activate, Deactivate, and Forget bound to that scope.

Persisting overrides with flags/nock

Swap flags.NewMemStore() for flags/nock when overrides need to survive restarts or sync across replicas. flags/nock supports both SQLite and Postgres through fletch/nock (fnock.Executor):

import (
	"github.com/fletchhq/flags"
	flagsnock "github.com/fletchhq/flags/nock"
)

if err := flagsnock.Migrate(ctx, db); err != nil {
	return err
}

store := flagsnock.New(db)
mgr := flags.NewManager(store)
import "github.com/fletchhq/flags"

store := flags.NewMemStore()
mgr := flags.NewManager(store)

flagsnock.Migrate(ctx, db) creates the feature_flags(flag, scope, value) table with primary key (flag, scope) if it does not exist. If your application manages DDL in migration files instead of at startup, copy flagsnock.Schema directly into a migration.

Gating HTTP and Fletch router routes

Protect routes with flags.Require, flags.RequireAny, or flags.RequireAnyWith. Supply a flags.ScopeFunc (func(r *http.Request) flags.Scope) to pick the scope per request; returning nil (or passing a nil function) evaluates flags.Global.

scopeFromReq := func(r *http.Request) flags.Scope {
	return flags.UserScope(currentUserID(r))
}

r.Use(flags.MemoizeMiddleware)

r.Handle("GET /billing/v2",
	flags.Require(mgr, "billing_v2", scopeFromReq,
		flags.WithFallback(legacyBillingHandler),
		flags.WithErrorHandler(func(w http.ResponseWriter, r *http.Request, err error) {
			http.Error(w, "flag check failed", http.StatusServiceUnavailable)
		}),
	)(v2BillingHandler),
)

Require, RequireAny, and RequireAnyWith work with both net/http and fletch/router, and they attach a request cache automatically if the request does not already have one. By default, inactive flags return 404 Not Found and evaluation errors return 500 Internal Server Error.

Checking flags in Crest and Go templates

Build a template function map for the current request with flags.TemplateFuncs(ctx, mgr, scope):

funcs := flags.TemplateFuncs(req.Context(), mgr, flags.UserScope(user.ID))

The returned map provides flagActive(name) bool and flagValue(name) any. Both treat store or evaluation errors as off (false and nil) so a broken flag store hides a feature instead of failing the page render. Pass a context wrapped by MemoizeMiddleware or WithRequestCache so repeated template checks hit the store once.

Building an admin or Sight management view

github.com/fletchhq/flags does not ship a dedicated Sight plugin, because flag storage is a single table (feature_flags) and every read/write operation is already exposed on Manager and Store. To inspect or toggle flags inside a Sight admin page or internal tool, combine mgr.Names(), mgr.Store().List(ctx, flag), mgr.Set, mgr.SetForEveryone, mgr.Forget, and mgr.Purge:

// List registered flags and all stored overrides sorted by flag, then scope
defined := mgr.Names()
entries, err := mgr.Store().List(ctx, "")

If you implement a custom Store, call flags.SortEntries(entries) inside List so entries follow the contract order (by Flag, then Scope).

Advanced usage

Testing with flagstest

github.com/fletchhq/flags/flagstest provides an in-memory *flagstest.Tester that embeds *flags.Manager with WithAllowUnknown() enabled, so you can drop it into any handler or service expecting *flags.Manager:

func TestBillingV2Handler(t *testing.T) {
	tf := flagstest.New(t)
	tf.Force("billing_v2", true)
	tf.ForceFor("theme", flags.UserScope("u_1"), "dark")
	defer tf.Reset()

	// Exercise handlers using tf.Manager...
}

Force sets a value on Everyone (and auto-defines the flag via DefineLike if unregistered), ForceFor targets one Scope, and Reset purges all forced and stored values while keeping flag definitions intact.

If you write your own flags.Store backend (such as Redis or a custom table), run the shared contract suite against it:

func TestCustomFlagStore(t *testing.T) {
	flagstest.RunStoreContract(t, func(tb testing.TB) flags.Store {
		return newMyStore(tb)
	})
}

Reference

Manager, Flag, and Scoped methods

Symbol Purpose
NewManager(store, opts...) Creates a *Manager configured with Option values (WithAllowUnknown())
Define[V] / DefineBool / mgr.Define Registers a flag and returns a typed Flag[V] (BoolFlag)
DefineLike(mgr, name, sample) Registers a zero-value flag matching sample's runtime type if absent
Flag[V].Name() / Value / Active / Set / Forget Typed flag inspection, reads, overrides, and reset
Value[V](ctx, mgr, name, scope) Reads a flag by name into type V (ErrTypeMismatch on mismatch)
mgr.Active / mgr.AllActive Checks whether one flag or all defined flags are active for a scope
mgr.Set / Activate / Deactivate / SetForEveryone Persists typed, boolean, or global Everyone overrides
mgr.Forget(ctx, name, scope) / mgr.Purge(ctx, names...) Deletes one stored value or purges all stored values for named (or all) flags
mgr.For(scope) / ScopedValue[V] Returns a Scoped view bound to one Scope
mgr.Names() / mgr.Store() / mgr.FlushCache(ctx) Lists sorted flag names, returns the backing Store, or clears the request cache

Scopes, resolvers, middleware, and errors

Symbol Category Behavior
Global / Everyone Scope App-wide default scope ("global") and global override scope ("*")
UserScope / UserIDScope / TeamScope / StringScope Scope Keyed scopes (user:<id>, team:<id>, <kind>:<id>)
Rollout(pct) / RolloutVariants(variants...) / Const(v) Resolver[V] Deterministic FNV-1a rollouts, weighted variants, or constant values
FlagName(ctx) Resolver helper Returns the name of the flag currently being resolved
MemoizeMiddleware / WithRequestCache(ctx) Caching Request-scoped memoization with automatic write invalidation
Require / RequireAny / RequireAnyWith Middleware HTTP and fletch/router route gates accepting RequireOption (WithFallback, WithErrorHandler)
TemplateFuncs(ctx, mgr, scope) Templates Returns flagActive and flagValue helpers
SortEntries(entries) Store helper Sorts []Entry by Flag, then Scope
ErrUnknownFlag / ErrTypeMismatch Errors Returned for undefined flags or mismatched value types