flags

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

flags

Typed feature flags for Go services: boolean and rich-value flags, scoped overrides, deterministic percentage rollouts and variants, per-request memoization, HTTP route gates, and Crest template helpers.

Pure Go, CGO_ENABLED=0, with only the standard library in the root module. It works with any net/http router and is the feature-flag layer for Fletch.

import "github.com/fletchhq/flags"

mgr := flags.NewManager(flags.NewMemStore())
newCheckout := flags.DefineBool(mgr, "new_checkout", flags.Rollout(25))

active, err := newCheckout.Active(ctx, flags.UserScope(userID))
  • Define[V], DefineBool, and DefineLike register typed flags with Resolver[V] defaults (Rollout, RolloutVariants, Const, or custom functions).
  • Scopes target Global, Everyone, or any Scope (UserScope, TeamScope, UserIDScope, StringScope, or your own type). A nil scope resolves as Global.
  • WithRequestCache and MemoizeMiddleware cache evaluations for the life of a request and invalidate automatically on writes (Set, Forget, Purge, FlushCache).
  • Require, RequireAny, and RequireAnyWith gate net/http and fletch/router handlers behind flags, with WithFallback and WithErrorHandler overrides.
  • TemplateFuncs exposes flagActive and flagValue to Crest and html/template views.
  • flags/nock persists overrides to SQLite or Postgres via fletch/nock, and flags/flagstest provides a test manager and store contract suite.

Packages

Package Purpose Dependencies
github.com/fletchhq/flags Manager, typed flags, scopes, resolvers, Store, MemStore, request memoization, HTTP middleware, template helpers Standard library only
github.com/fletchhq/flags/nock Persistent SQLite and Postgres Store backed by feature_flags(flag, scope, value), plus Schema and Migrate flags, fletch/nock
github.com/fletchhq/flags/flagstest *Tester (Force, ForceFor, Reset) and RunStoreContract for custom stores flags

Docs & agent skills

See docs/flags.md for the guide and skills/flags/SKILL.md for agent guidance. When this module is in a Fletch app's go.mod, fletch ax sync and fletch docs automatically discover and sync its docs/ and skills/.

Development

GOWORK=off CGO_ENABLED=0 go test -race -count=1 ./...
CGO_ENABLED=0 scripts/lint.sh   # golangci-lint v2.15.0

License

MIT or Apache-2.0, at your option. See LICENSE-MIT and LICENSE-APACHE.

Documentation

Overview

Package flags is a feature flag engine: flags are defined in code with a resolver, evaluated per scope (a user, a team, anything with a key), and the resolved value is persisted in a Store so it stays stable until changed.

The root package depends only on the standard library. Persistent stores live in subpackages (flags/nock) and test helpers in flags/flagstest.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnknownFlag is returned for a flag that was never defined.
	ErrUnknownFlag = errors.New("flags: unknown flag")
	// ErrTypeMismatch is returned when a value does not have the flag's type.
	ErrTypeMismatch = errors.New("flags: type mismatch")
)

Functions

func DefineLike

func DefineLike(m *Manager, name string, sample any) error

DefineLike defines a flag called name whose type is the type of sample and whose resolver yields that type's zero value. It does nothing if name is already defined. It exists for tools and tests that learn a flag's type only at run time; application code uses Define.

func FlagName

func FlagName(ctx context.Context) string

FlagName returns the name of the flag whose resolver is running, or "" when ctx does not belong to a resolver.

func MemoizeMiddleware

func MemoizeMiddleware(next http.Handler) http.Handler

MemoizeMiddleware gives every request its own request cache.

func Require

func Require(m *Manager, name string, scope ScopeFunc, opts ...RequireOption) func(http.Handler) http.Handler

Require returns middleware that serves the route only when the flag is active for the request's scope, and the fallback (404 by default) otherwise. It works with net/http and with github.com/fletchhq/fletch/router, whose middleware are func(http.Handler) http.Handler. The request gets a request cache if it has none.

func RequireAny

func RequireAny(m *Manager, scope ScopeFunc, names ...string) func(http.Handler) http.Handler

RequireAny is Require satisfied by any one of names.

func RequireAnyWith

func RequireAnyWith(m *Manager, scope ScopeFunc, names []string, opts ...RequireOption) func(http.Handler) http.Handler

RequireAnyWith is RequireAny with options.

func ScopedValue

func ScopedValue[V any](ctx context.Context, s Scoped, name string) (V, error)

ScopedValue returns the value of a flag for the scope bound to s.

func SortEntries

func SortEntries(es []Entry)

SortEntries orders entries by flag, then scope, the order List promises.

func TemplateFuncs

func TemplateFuncs(ctx context.Context, m *Manager, scope Scope) map[string]any

TemplateFuncs returns helper functions for templates, bound to ctx and scope: flagActive(name) bool and flagValue(name) any. Both treat an evaluation error as off (false and nil), so a broken store hides a feature instead of failing the page. Merge the map into the template engine's function set; pass a context from WithRequestCache so repeated calls in one render read the Store once.

func Value

func Value[V any](ctx context.Context, m *Manager, name string, scope Scope) (V, error)

Value returns the flag's value for scope as type V.

func WithRequestCache

func WithRequestCache(ctx context.Context) context.Context

WithRequestCache returns a context that memoizes flag values: within it, each (flag, scope) pair is read from the Store at most once. Set, Forget, Purge, and FlushCache on a Manager invalidate the memoized entries. A context that already has a request cache is returned unchanged.

Types

type BoolFlag

type BoolFlag = Flag[bool]

BoolFlag is a Flag that is either on or off.

func DefineBool

func DefineBool(m *Manager, name string, r Resolver[bool]) BoolFlag

DefineBool is Define for a boolean flag.

type Entry

type Entry struct {
	Flag  string
	Scope string
	Value []byte
}

Entry is one stored flag value.

type Flag

type Flag[V any] struct {
	// contains filtered or unexported fields
}

Flag is a defined flag whose values have type V.

func Define

func Define[V any](m *Manager, name string, r Resolver[V]) Flag[V]

Define registers a flag called name with the manager and returns a typed handle. It panics if name is empty, r is nil, or name is already defined.

func (Flag[V]) Active

func (f Flag[V]) Active(ctx context.Context, scope Scope) (bool, error)

Active reports whether the flag is on for scope.

func (Flag[V]) Forget

func (f Flag[V]) Forget(ctx context.Context, scope Scope) error

Forget drops the stored value for scope so the resolver runs again.

func (Flag[V]) Name

func (f Flag[V]) Name() string

Name returns the flag's name.

func (Flag[V]) Set

func (f Flag[V]) Set(ctx context.Context, scope Scope, v V) error

Set stores v as the flag's value for scope.

func (Flag[V]) Value

func (f Flag[V]) Value(ctx context.Context, scope Scope) (V, error)

Value returns the flag's value for scope.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager evaluates flags against a Store.

func NewManager

func NewManager(store Store, opts ...Option) *Manager

NewManager returns a Manager that persists values in store.

func (*Manager) Activate

func (m *Manager) Activate(ctx context.Context, name string, scope Scope) error

Activate turns a boolean flag on for scope.

func (*Manager) Active

func (m *Manager) Active(ctx context.Context, name string, scope Scope) (bool, error)

Active reports whether the flag is on for scope. A boolean flag is on when true; a flag of any other type is on when its value is not the zero value.

func (*Manager) AllActive

func (m *Manager) AllActive(ctx context.Context, scope Scope) ([]string, error)

AllActive returns the sorted names of the defined flags that are on for scope.

func (*Manager) Deactivate

func (m *Manager) Deactivate(ctx context.Context, name string, scope Scope) error

Deactivate turns a boolean flag off for scope.

func (*Manager) Define

func (m *Manager) Define(name string, r Resolver[bool]) BoolFlag

Define registers a boolean flag.

func (*Manager) FlushCache

func (m *Manager) FlushCache(ctx context.Context)

FlushCache empties the request cache of ctx. It does nothing when ctx has none.

func (*Manager) For

func (m *Manager) For(scope Scope) Scoped

For returns a view of the manager for scope.

func (*Manager) Forget

func (m *Manager) Forget(ctx context.Context, name string, scope Scope) error

Forget removes the stored value for scope, so the resolver runs again on the next read. Forgetting Everyone removes the override.

func (*Manager) Names

func (m *Manager) Names() []string

Names returns the defined flag names in order.

func (*Manager) Purge

func (m *Manager) Purge(ctx context.Context, names ...string) error

Purge removes every stored value of the named flags, or of all flags when none is named.

func (*Manager) Set

func (m *Manager) Set(ctx context.Context, name string, scope Scope, value any) error

Set stores value as the flag's value for scope. value must have the flag's type.

func (*Manager) SetForEveryone

func (m *Manager) SetForEveryone(ctx context.Context, name string, value any) error

SetForEveryone stores value as an override that wins over every scope's own value and over the resolver.

func (*Manager) Store

func (m *Manager) Store() Store

Store returns the manager's Store.

type MemStore

type MemStore struct {
	// contains filtered or unexported fields
}

MemStore is a Store held in memory.

func NewMemStore

func NewMemStore() *MemStore

NewMemStore returns an empty MemStore.

func (*MemStore) Delete

func (s *MemStore) Delete(_ context.Context, flag, scope string) error

Delete implements Store.

func (*MemStore) Get

func (s *MemStore) Get(_ context.Context, flag, scope string) ([]byte, bool, error)

Get implements Store.

func (*MemStore) List

func (s *MemStore) List(_ context.Context, flag string) ([]Entry, error)

List implements Store.

func (*MemStore) Purge

func (s *MemStore) Purge(_ context.Context, flags ...string) error

Purge implements Store.

func (*MemStore) Set

func (s *MemStore) Set(_ context.Context, flag, scope string, value []byte) error

Set implements Store.

type Option

type Option func(*Manager)

Option configures a Manager.

func WithAllowUnknown

func WithAllowUnknown() Option

WithAllowUnknown makes Active report false, and Set and Forget do nothing, for flags that were never defined, instead of returning ErrUnknownFlag.

type RequireOption

type RequireOption func(*requireConfig)

RequireOption configures Require.

func WithErrorHandler

func WithErrorHandler(fn func(w http.ResponseWriter, r *http.Request, err error)) RequireOption

WithErrorHandler sets what happens when evaluating a flag fails. The default responds 500.

func WithFallback

func WithFallback(h http.Handler) RequireOption

WithFallback sets the handler that runs instead of the route when the flag is off. The default responds 404.

type Resolver

type Resolver[V any] func(ctx context.Context, scope Scope) (V, error)

Resolver computes a flag's value for a scope the first time it is needed. The result is stored, so the resolver does not run again for that scope until the value is forgotten. FlagName(ctx) returns the flag's name.

func Const

func Const[V any](v V) Resolver[V]

Const returns a resolver that always yields v.

func Rollout

func Rollout(pct float64) Resolver[bool]

Rollout returns a resolver that is true for roughly pct percent of scopes. A scope's bucket depends only on the flag name and the scope key, so a scope keeps its answer across calls and raising pct never turns anyone off. Values of pct at or below 0 match nobody; at or above 100 match everyone.

func RolloutVariants

func RolloutVariants[V any](variants ...Variant[V]) Resolver[V]

RolloutVariants returns a resolver that assigns each scope one of the variants in proportion to its weight, deterministically per flag and scope. Variants with non-positive weight are never chosen; with no positive weight the zero V is returned.

type Scope

type Scope interface {
	// ScopeKey returns a stable identifier such as "user:42".
	ScopeKey() string
}

Scope is what a flag is evaluated for: a user, a team, a tenant.

var (
	// Global is the scope of flags that do not depend on who asks. A nil
	// Scope is treated as Global.
	Global Scope = keyScope(globalKey)

	// Everyone is the scope of an override that applies to every scope.
	// Setting a flag for Everyone wins over per-scope values and resolvers.
	Everyone Scope = keyScope(everyoneKey)
)

func StringScope

func StringScope(kind, id string) Scope

StringScope returns a scope keyed "kind:id".

func TeamScope

func TeamScope(id string) Scope

TeamScope returns the scope of the team with the given ID.

func UserIDScope

func UserIDScope(id int64) Scope

UserIDScope is UserScope for numeric IDs.

func UserScope

func UserScope(id string) Scope

UserScope returns the scope of the user with the given ID.

type ScopeFunc

type ScopeFunc func(r *http.Request) Scope

ScopeFunc picks the scope a request is evaluated for, typically the signed in user. A nil ScopeFunc, or one that returns nil, means Global.

type Scoped

type Scoped struct {
	// contains filtered or unexported fields
}

Scoped is a Manager bound to one scope.

func (Scoped) Activate

func (s Scoped) Activate(ctx context.Context, name string) error

Activate turns the flag on for the bound scope.

func (Scoped) Active

func (s Scoped) Active(ctx context.Context, name string) (bool, error)

Active reports whether the flag is on for the bound scope.

func (Scoped) AllActive

func (s Scoped) AllActive(ctx context.Context) ([]string, error)

AllActive returns the names of the flags that are on for the bound scope.

func (Scoped) Deactivate

func (s Scoped) Deactivate(ctx context.Context, name string) error

Deactivate turns the flag off for the bound scope.

func (Scoped) Forget

func (s Scoped) Forget(ctx context.Context, name string) error

Forget drops the bound scope's stored value.

func (Scoped) Set

func (s Scoped) Set(ctx context.Context, name string, value any) error

Set stores value for the bound scope.

type Store

type Store interface {
	// Get returns the value stored for flag and scope; ok is false when none
	// is stored.
	Get(ctx context.Context, flag, scope string) (value []byte, ok bool, err error)
	// Set stores value, replacing any earlier value.
	Set(ctx context.Context, flag, scope string, value []byte) error
	// Delete removes one value. Deleting a missing value is not an error.
	Delete(ctx context.Context, flag, scope string) error
	// List returns the entries of flag ordered by scope, or the entries of
	// every flag ordered by flag then scope when flag is empty.
	List(ctx context.Context, flag string) ([]Entry, error)
	// Purge removes every value of the named flags, or of all flags when none
	// is named.
	Purge(ctx context.Context, flags ...string) error
}

Store persists resolved flag values, keyed by flag name and scope key. Values are opaque encoded bytes. Implementations must be safe for concurrent use.

type Variant

type Variant[V any] struct {
	Value  V
	Weight float64
}

Variant is one outcome of RolloutVariants with its relative weight.

Directories

Path Synopsis
Package flagstest helps test code that uses flags: an in-memory manager with forced values, and a contract suite for Store implementations.
Package flagstest helps test code that uses flags: an in-memory manager with forced values, and a contract suite for Store implementations.
Package nock is a flags.Store backed by a SQL database through github.com/fletchhq/fletch/nock.
Package nock is a flags.Store backed by a SQL database through github.com/fletchhq/fletch/nock.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL