appconfig

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 16 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.

Documentation

Overview

Package appconfig loads layered JSON configuration for Visdom/Orca services.

Load

Load reads app.default.json from an `fs.FS`. If Options.Environment is not empty, Load also reads app.<environment>.json. Load merges the second file over the first. Callers select the environment. A common choice is os.Getenv("ENV"):

//go:embed config/*.json
var configFS embed.FS

sub, err := fs.Sub(configFS, "config")
if err != nil {
	return err
}

cfg, err := appconfig.Load(sub, appconfig.Options{
	Environment:   os.Getenv("ENV"),
	Substitutions: map[string]string{"BUILD": build},
	GCPProjectID:  os.Getenv("GCP_PROJECT_ID"),
})
if err != nil {
	return err
}
defer cfg.Close()

host, err := cfg.Lookup(ctx, "database.host")

For files on disk, pass os.DirFS:

cfg, err := appconfig.Load(os.DirFS("/etc/myapp"), appconfig.Options{})

Substitution

Load scans each source file for ${name} references before JSON decoding. Load replaces each reference with the value from Options.Substitutions. Load inserts the value as raw text. The value must be valid JSON for its position. Use a quoted string inside a string value. Use a bare number after a colon. Substitution does not repeat on inserted values. Use `$${name}` for a literal `${name}`. Load removes one leading dollar sign. An escaped reference does not need a parameter.

Load fails on these errors:

  • an undefined parameter
  • an empty or malformed name
  • an unterminated reference

The error names the parameter and the file.

Merge rules

Nested JSON objects merge recursively. Arrays, scalars, and null values in the environment file replace the base value. Load adds keys that exist only in the environment file. The merged tree is private and immutable.

Lookup

Config.Lookup takes a dot path. Empty paths and empty segments are invalid. Strings, numbers, and booleans convert to text. Number literals keep their original form. Objects and arrays report ErrType.

Config.LookupList requires an array of strings. It resolves each element with the same rules. It returns a new slice.

Lookup errors are sentinels:

Use errors.Is to classify them.

Value resolvers

Values of the form PREFIX:reference resolve on every lookup:

ENV:NAME                              environment variable
GCPSECRET:SECRET/VERSION              Secret Manager payload
GCPSECRETJSON:SECRET/VERSION/FIELD    scalar field of a JSON payload

Prefix matching ignores case. Lookup trims spaces around the prefix and reference. Unknown prefixes return the stored string unchanged. This includes URLs such as https://...

ENV reads the variable at lookup time. An unset variable reports ErrNotFound. A variable with an empty value returns "".

GCP secret versions accept latest or a positive number. The `v1` or `V1` form in existing dfconfig files is accepted and normalized to 1. GCPSECRETJSON returns only a string, number, or boolean field. Other shapes report ErrNotFound, ErrNull, or ErrType. Malformed references fail with a descriptive error.

If Options.DisableGCPSecrets is true, every GCP reference returns the stored string. No Secret Manager client is created.

GCP Secret Manager

Options.GCPProjectID is required only when enabled GCP resolution first needs a client. Load validates a non-empty project ID when GCP is enabled. The ID must be 6 to 30 characters. It must start with a lowercase letter. It can contain lowercase letters, digits, and hyphens. The client starts lazily and serves the whole Config lifetime. `lazy.Lazy` guards startup. Concurrent first lookups share one startup attempt. Every lookup calls Secret Manager with the caller's context. Payloads are not cached. A rotated secret is visible on the next lookup. A failed client startup retries on the next lookup, as `lazy.Lazy` describes.

`lazy.Lazy` uses the first caller's context for startup. Pass a context with enough lifetime for the first lookup. Do not pass a context that is cancelled immediately.

Close is idempotent. It waits for active lookups. It closes only a client that already exists. Later lookups return ErrClosed. If a close fails, the Config stays open. The caller can retry Close.

Concurrency and logs

Concurrent lookups are safe. The package writes no logs. It never prints the merged configuration or resolved values. Errors may name configuration paths, secret ids, versions, and resource names. Errors never contain payloads.

Lookup holds a read lock while it resolves. Set a deadline on the lookup context. Close waits for active lookups. Do not call Close on a request path.

Differences from Java dfconfig

This package differs from the Java library in several ways:

  • The caller supplies the environment. Load does not read ENV.
  • Lookups return sentinel errors. They do not return nullable strings.
  • Substitution fails fast. Unresolved references do not remain in place.
  • The caller owns Close. The package does not create a client per lookup.
  • List lookups require string elements. They do not use unchecked casts.
  • Numbers keep their literal form.
  • The merged configuration is never logged.

See docs/adr/adr-appconfig.md for the full decision record.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound reports a missing configuration path, an unset ENV
	// variable, or a missing field in a JSON secret.
	ErrNotFound = errors.New("appconfig: not found")
	// ErrNull reports a path that resolves to a JSON null value.
	ErrNull = errors.New("appconfig: null value")
	// ErrType reports a value that cannot be converted to the requested shape.
	ErrType = errors.New("appconfig: unexpected value type")
	// ErrClosed reports a lookup on a closed Config.
	ErrClosed = errors.New("appconfig: config is closed")
)

Sentinel errors returned by Config lookups. Use errors.Is to classify them.

Functions

This section is empty.

Types

type Config

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

Config is a loaded, immutable configuration tree.

A Config must not be copied after first use. Callers own the lifecycle and must call Close when finished.

func Load

func Load(fsys fs.FS, opts Options) (*Config, error)

Load reads app.default.json from fsys and, when opts.Environment is non-empty, merges app.<Environment>.json over it.

Substitution is applied to each file before JSON decoding. Loading performs no environment or secret resolution; that happens in Lookup and LookupList.

func (*Config) Close

func (c *Config) Close() error

Close releases resources owned by the Config. It is idempotent; later lookups return ErrClosed. If a client close fails, Close returns the error and leaves the Config open so the caller can retry.

func (*Config) Lookup

func (c *Config) Lookup(ctx context.Context, path string) (string, error)

Lookup resolves a dot-path scalar and applies the standard value resolvers.

Strings, numbers, and booleans convert to text. Objects and arrays report ErrType. A missing path reports ErrNotFound, a JSON null reports ErrNull. Resolver references are evaluated on every call; unknown prefixes and disabled resolvers return the stored string unchanged.

func (*Config) LookupList

func (c *Config) LookupList(ctx context.Context, path string) ([]string, error)

LookupList resolves a dot-path array and resolves every element as a string. It always returns a new slice. Non-string elements and non-array values report ErrType.

type Options

type Options struct {
	// Environment selects the optional app.<Environment>.json overlay.
	// Leave it empty to load only app.default.json.
	Environment string

	// Substitutions supplies values for ${name} references found in every
	// JSON source. Each value is inserted verbatim and must be valid JSON
	// text for the position where the reference appears.
	Substitutions map[string]string

	// GCPProjectID is the Google Cloud project used to build Secret Manager
	// resource names. It is required only when an enabled GCP resolver
	// reference is looked up.
	GCPProjectID string

	// DisableGCPSecrets leaves GCP resolver references as raw strings and
	// never creates a Secret Manager client.
	DisableGCPSecrets bool
}

Options configures Load.

Jump to

Keyboard shortcuts

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