gonf

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

gonf

The Go gopher lifting a gear that forms the O of GONF

Go Reference Build Status Go Version License

gonf fills your Go structs from files, environment and flags, and checks them before your service starts.

  • Typed structs: no string lookups, no casts
  • Fail fast: every error at start, with file and line
  • Layering: defaults, files, .env, env and flags, each one on top
  • Any profiles: dev, staging, local, combined
  • Explain: see where each value came from
  • Env without binding: APP_DB_URL sets app.db.url, typos warned
  • Formats: properties, JSON, YAML, .env
  • Sources: files, env, flags, secret mounts, your own
  • No secret logging: **** in logs, errors and docs
  • Expressions: ${app.db.host}, ${file::/run/secrets/db}
  • Safe reload: a broken change never goes live
  • Generated docs: key reference and JSON Schema
  • Extensible: own sources, formats and functions
  • Library modules: packages bring their own config
  • Zero dependencies: core is standard library only

Getting started

go get github.com/efuturetoday/gonf

Describe your settings as a struct. default and desc are optional:

type Config struct {
	Port int `default:"8080" desc:"HTTP port"`
	DB   struct {
		Host     string              `default:"localhost" desc:"database host"`
		URL      string              `desc:"connection string"`
		Password gonf.Secret[string] `default:"change-me"`
	}
}

var appConfig = gonf.NewMapping[Config]("app")

gonf.NewMapping ties the struct to the name app: the field DB.URL becomes the key app.db.url. Put values in config/app.properties:

app.port=8000
app.db.host=db.internal
app.db.url=postgres://${app.db.host}:5432/app

Load the configuration and read the struct in main.go:

func main() {
	cfg, err := boot.Load(context.Background(), boot.WithMappings(appConfig))
	if err != nil {
		log.Fatal(err)
	}

	for _, w := range cfg.Warnings() {
		log.Println("warning:", w)
	}

	c := appConfig.Get(cfg)
	fmt.Println("port:    ", c.Port)
	fmt.Println("db.url:  ", c.DB.URL)
	fmt.Println("password:", c.DB.Password)

	// go run . app.db.url
	if len(os.Args) > 1 {
		fmt.Println(cfg.Explain(os.Args[1]))
	}
}

The complete program is in examples/quickstart. Run it from that directory:

$ go run .
port:     8000
db.url:   postgres://db.internal:5432/app
password: ****

boot.Load found config/app.properties by itself. Now set a value with an environment variable. It wins over the file:

$ APP_PORT=9000 go run .
port:     9000
db.url:   postgres://db.internal:5432/app
password: ****

That is the whole idea: a struct, a file, and the environment on top.

Examples

Each example below runs against the quickstart program.

A mistake in the file

Say config/app.properties has a typo, ulr instead of url:

app.port=8000
app.db.host=db.internal
app.db.ulr=postgres://${app.db.host}:5432/app

The program stops at start and reports every problem, not only the first:

$ go run .
gonf: bind "app": 2 problems:
  app.db.url: required, no value
  app.db.ulr: unknown key, did you mean app.db.url? (from file:config/app.properties:3)

A wrong type is caught the same way, for example app.port=80x:

gonf: bind "app": app.port: invalid int "80x" (from file:config/app.properties:1)
Where does a value come from?

The quickstart prints cfg.Explain(key) for a key given on the command line:

$ APP_PORT=9000 go run . app.port
app.port = 9000 (env:APP_PORT)
  overrides 8000 (file:config/app.properties:1)
  default 8080 (main.go:30)

The first line is the value in use and where it comes from. The lines below show what it replaced, and the default from the struct tag. More in Where does a value come from?.

Profiles

A profile is a named set of values for one environment. Add config/app-dev.properties:

app.db.host=localhost

and start with GONF_PROFILE=dev:

$ GONF_PROFILE=dev go run . app.db.url
port:     8000
db.url:   postgres://localhost:5432/app
password: ****
app.db.url = postgres://localhost:5432/app (file:config/app.properties:3)

The profile file replaced app.db.host, and app.db.url, which refers to it, followed. More in Profiles.

Secrets

Password is a gonf.Secret[string], so it prints as **** with fmt, JSON, slog and in Explain. Your code gets the real value when it asks for it:

password := c.DB.Password.Value()

More in Secrets.

Expressions and functions

A value can refer to another key with ${...}, as app.db.url does with ${app.db.host}. A function takes the form ${name::argument}. Read the password from the environment variable DB_PASSWORD:

app.db.url=postgres://localhost/app
app.db.password=${env::DB_PASSWORD}
$ DB_PASSWORD=s3cret go run . app.db.password
port:     8080
db.url:   postgres://localhost/app
password: ****
app.db.password = **** (file:config/app.properties:2, via env)
  default **** (main.go:30)

If DB_PASSWORD is not set, the start fails with a message that names the key and the line. More in Sources.

Next steps

  • Profiles: %dev. keys, app-dev.properties, activating profiles.
  • Structs: names, defaults, optional fields, lists, maps, validation, unknown keys, and converters for types of other packages.
  • Secrets: gonf.Secret[T], what gets masked, and encrypted values.
  • Where does a value come from?: cfg.Explain shows the winning value, its file and line, and what it overrides; cfg.Warnings() and cfg.Sources() show what was skipped and loaded.
  • Configuration reference: generate a table of all keys with their environment variables, types and defaults, and a JSON Schema for editors.
  • Sources and formats: .properties, JSON, YAML, .env, the environment, flags, secret directories, expressions with functions such as what git knows, and your own Sources.
  • Reloading: boot.Watch keeps the configuration current when files change, and keeps the previous one if a change is invalid.

The API reference is on pkg.go.dev.

More programs in examples/:

gonf, viper or koanf?

All three load layered configuration. They differ in what they take care of for you.

gonf viper koanf
Shape typed structs, checked at start keys read by name, Unmarshal into structs you assemble providers and parsers
State no global state a global instance by default an instance you create
Keys case-sensitive case-insensitive case-sensitive
Environment matched against your structs derived by AutomaticEnv and BindEnv env provider with a transform callback

Choose gonf for services that want typed structs checked at start with all errors at once, the origin of every value (cfg.Explain), profiles, secrets, environment variables matched against the structs, and docs and a schema generated from the code. Choose viper for its large ecosystem and remote providers. Choose koanf if you want to assemble providers and parsers yourself with few opinions.

Coming from viper or koanf:

  • A Mapping per struct (gonf.NewMapping[Config]("app")) replaces Unmarshal. Unknown keys and missing values fail at start.
  • Environment names come from the keys (app.db.url is APP_DB_URL), so there is nothing to bind or transform.
  • Values may refer to others and call functions: ${app.db.host}, ${env::HOME}.

Contributing

Issues and pull requests are welcome. Before sending a change, run:

go vet ./...
go test -race ./...
golangci-lint run

format/yaml and cmd/gonf are modules of their own, so that gonf depends on the standard library only; run the same commands in their directories. go.work builds them against the gonf of this repository, and all three are released together under one version.

Pull requests are squashed into one commit named by their title, which follows Conventional Commits, such as feat(source): Verbatim or fix: profile of a reload. Releases and the changelog are made from these titles. Report vulnerabilities as described in SECURITY.md.

License

Apache License 2.0

The gonf logo is based on the Go gopher by Renée French, licensed under CC BY 4.0.

Documentation

Overview

Package gonf is a layered configuration library: values come from several Sources such as files and the environment, and are bound to typed structs that report every problem at once.

Configuration is read from several Sources. Each Source has an ordinal; for every key the value from the Source with the highest ordinal wins. If two Sources have the same ordinal, the one registered later wins.

A key prefixed with "%profile." such as "%dev.db.url" is a value for "db.url" that applies only while that profile is active (see WithProfiles). At equal ordinal a profile value beats the base value; a higher ordinal always wins, so an environment variable still overrides a profile value from a file.

Values may reference other keys with ${key} or ${key:default}; Get expands them.

A Mapping binds the keys under a prefix to a struct, such as "db.url" and "db.pool.max-size" to a DBConfig; Load binds every Mapping and reports all problems at once. A field of type Secret keeps its value out of fmt, JSON and log output.

Explain tells where the value of a key comes from and what it overrides, with secret values masked; Explanations does so for the whole configuration.

Describe lists the keys that the Mappings read, with their types, defaults and descriptions, without reading any value; WriteMarkdown turns the list into the configuration reference of an application.

Sources that need configuration themselves, such as a Vault Source whose address is configured in a file, are created by a SourceFactory with a Mapping of its own (see NewFactory).

Watch keeps the configuration current: when a Source that implements Watcher reports a change, it loads everything again and, if that succeeds, replaces the Config that Live.Config returns.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidSourceName = errors.New("gonf: source name must start with a scheme such as \"file:\"")

ErrInvalidSourceName is reported, wrapped in a SourceError, for a Source whose name has no valid scheme (see Scheme).

View Source
var ErrNameConflict = errors.New("gonf: keys with the same name")

ErrNameConflict is wrapped by the error Describe returns for keys that have the same name in a Source, see WarnNameConflict.

View Source
var ErrNotFound = errors.New("gonf: key not found")

ErrNotFound is returned by Get when the requested key has no value.

Functions

func Encode

func Encode(prefix string, v any) (map[string]string, error)

Encode returns the values of v, a struct, under the keys that a Mapping of its type at prefix binds: the inverse of Load, so that a Source holding the values, escaped with Escape, binds to v again. A Secret gives its value; a nil pointer gives no key.

type Conn struct {
	URL      string
	Password gonf.Secret[string]
}
gonf.Encode("db", Conn{URL: "postgres://db/app", Password: gonf.NewSecret("s3cret")})
// map[db.password:s3cret db.url:postgres://db/app]

Encode takes the types Load reads without a converter: strings, booleans, numbers, time.Duration, a type with MarshalText and UnmarshalText, Secret[T] of these, pointers, structs, lists, given as indexed keys such as hosts[0], and maps. An empty list or map gives no key, so it binds as nil. An empty value gives no key either, as Load reads an empty value as none: the field gets its default. An empty element of a list is an error.

func Escape

func Escape(s string) string

Escape returns s with every "${" written as "$${", so that a Source holding it gives s back as it is, not expanded: for values that come from elsewhere, such as those of Encode or of another process.

func Scheme

func Scheme(name string) (string, bool)

Scheme returns the scheme of a Source name, the part before the first ':', and whether name has a valid scheme. A valid scheme has at least two characters, starts with a letter and contains only letters, digits, '+', '-' and '.' (RFC 3986). The two-character minimum keeps Windows paths such as "C:\app.properties" from passing as a scheme.

func WriteMarkdown

func WriteMarkdown(w io.Writer, props []Property) error

WriteMarkdown writes props as a Markdown table, such as for a README. A required key shows "required" as its default.

Types

type AnyMapping

type AnyMapping interface {
	Prefix() string
	// contains filtered or unexported methods
}

AnyMapping is a *Mapping of any type, as accepted by WithMappings.

type BindError

type BindError struct {
	Prefix   string
	Problems []*Problem
}

BindError reports every key of one Mapping that Load could not bind.

Example
package main

import (
	"context"
	"fmt"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	type DB struct {
		URL     string
		MaxSize int
	}
	_, err := gonf.Load(context.Background(),
		gonf.WithMappings(gonf.NewMapping[DB]("db")),
		gonf.WithSources(memory.New(
			map[string]string{"db.max-size": "ten", "db.ulr": "postgres://localhost/app"},
			source.WithName("file:app.properties"),
		)),
	)
	fmt.Println(err)
}
Output:
gonf: bind "db": 3 problems:
  db.url: required, no value
  db.max-size: invalid int "ten" (from file:app.properties)
  db.ulr: unknown key, did you mean db.url? (from file:app.properties)

func (*BindError) Error

func (e *BindError) Error() string

Error lists the Problems, one per line if there are several.

func (*BindError) Unwrap

func (e *BindError) Unwrap() []error

Unwrap returns the Problems, so errors.Is(err, ErrNotFound) reports a missing value.

type Config

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

Config is an immutable snapshot of all loaded values. It is safe for concurrent use.

func Load

func Load(ctx context.Context, opts ...Option) (*Config, error)

Load reads all Sources once and merges them into a Config.

Load works in two phases. First it loads the Sources given with WithSources, settles the active profiles, loads the Sources of WithProfileSources and binds the Mappings of the factories. Then it runs every SourceFactory and loads the Sources they return. If the first phase fails, no factory runs. Finally it binds all Mappings and returns the BindErrors of all of them together.

Every Source is loaded even if an earlier one fails; all failures are returned together, as SourceErrors joined with errors.Join.

Example
package main

import (
	"context"
	"fmt"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	cfg, err := gonf.Load(context.Background(),
		gonf.WithProfiles("dev"),
		gonf.WithSources(
			memory.Defaults(map[string]string{"db.pool.max-size": "10"}),
			memory.New(map[string]string{
				"db.url":           "postgres://prod-db/app",
				"%dev.db.url":      "postgres://localhost/app",
				"db.pool.max-size": "20",
			}, source.WithName("file:app.properties"), source.WithOrdinal(100)),
		),
	)
	if err != nil {
		panic(err)
	}
	for _, key := range cfg.Keys() {
		v, _ := cfg.Lookup(key)
		fmt.Printf("%s = %s (from %s, profile %q)\n", key, v.Raw, v.Origin.Source, v.Origin.Profile)
	}
}
Output:
db.pool.max-size = 20 (from file:app.properties, profile "")
db.url = postgres://localhost/app (from file:app.properties, profile "dev")

func (*Config) Candidates

func (c *Config) Candidates(key string) []Value

Candidates returns every value for key from all Sources and active profiles, the winner first.

func (*Config) Eval

func (c *Config) Eval(expr string) (string, error)

Eval expands the expressions in expr as Get expands a value, such as

cfg.Eval("${env::HOME}/logs")
cfg.Eval("postgres://${db.host:localhost}/app")

A missing reference is an error that does not match ErrNotFound. Eval records no reads, and Functions get the zero Origin.

func (*Config) Explain

func (c *Config) Explain(key string) Explanation

Explain tells where the value of key comes from, including the values it overrides and the default of a Mapping, and what the key is.

func (*Config) Explanations

func (c *Config) Explanations() []Explanation

Explanations explains every key of the Sources and every key a Mapping bound or referenced that has a value or a default, sorted by key. Environment variables that match no key, such as PATH, are no keys.

Example
package main

import (
	"context"
	"fmt"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	type DBConfig struct {
		Password gonf.Secret[string]
		Pool     struct {
			MaxSize int `default:"10"`
		}
	}
	cfg, err := gonf.Load(context.Background(),
		gonf.WithMappings(gonf.NewMapping[DBConfig]("db")),
		gonf.WithSources(
			memory.New(map[string]string{
				"app.dsn":     "postgres://app:${db.password}@localhost/app",
				"db.password": "hunter2",
			}, source.WithName("file:app.properties"), source.WithOrdinal(100)),
			memory.New(map[string]string{
				"app.dsn": "postgres://app:${db.password}@prod/app",
			}, source.WithName("memory:overrides")),
		),
	)
	if err != nil {
		panic(err)
	}
	for _, e := range cfg.Explanations() {
		fmt.Println(e)
	}
}
Output:
app.dsn = postgres://app:****@prod/app (memory:overrides)
  overrides postgres://app:${db.password}@localhost/app (file:app.properties)
db.password = **** (file:app.properties)
db.pool.max-size = 10 (default, example_test.go:190)

func (*Config) Get

func (c *Config) Get(key string) (string, error)

Get returns the value of key with all expressions expanded.

${key}          value of key, an error if it has none
${key:default}  value of key, or default (itself expanded) if it has none
${name::arg}    result of the Function name for arg (itself expanded)
$${             a literal "${"

References are resolved like Lookup, so profiles apply. An environment variable is found only under a key it matched, such as ${db.port} for DB_PORT (see MappedSource); ${env::HOME} reads any variable if the env Function is registered. If key itself has no value, the error matches ErrNotFound; a missing reference, a cycle, a failing Function or a malformed expression is reported with the keys involved. One Get resolves at most 1000 references and builds at most 1 MiB; beyond that it returns an error.

Example
package main

import (
	"context"
	"fmt"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	cfg, err := gonf.Load(context.Background(), gonf.WithSources(memory.New(map[string]string{
		"db.host": "localhost",
		"db.url":  "postgres://${db.host}:${db.port:5432}/app",
	})))
	if err != nil {
		panic(err)
	}
	url, err := cfg.Get("db.url")
	if err != nil {
		panic(err)
	}
	fmt.Println(url)
}
Output:
postgres://localhost:5432/app

func (*Config) Keys

func (c *Config) Keys() []string

Keys returns all known keys, sorted. Values of active profiles appear under their base key. Environment variables appear under the keys they matched (see MappedSource), such as db.url for DB_URL.

func (*Config) Lookup

func (c *Config) Lookup(key string) (Value, bool)

Lookup returns the winning value for key. The value is raw: expressions such as ${db.host} are not expanded (see Get). Keys with a profile prefix are not found directly, only through their base key.

func (*Config) Profiles

func (c *Config) Profiles() []string

Profiles returns the active profiles in the order given, so the last one wins.

func (*Config) Properties

func (c *Config) Properties() []Property

Properties returns the Properties of the Mappings, in the order of the Mappings and their fields, as Describe returns them for the options of Load: every key a Mapping reads, also those without a value.

func (*Config) Sources

func (c *Config) Sources() []SourceInfo

Sources returns the loaded Sources, the highest priority first: the order in which they win a key. Of equal ordinals the Source registered later comes first.

func (*Config) Warnings

func (c *Config) Warnings() []Warning

Warnings returns what Load noticed and did not treat as an error, see Warning: first those of the Sources in priority order, by name, then the name conflicts of the Mappings.

type Explanation

type Explanation struct {
	Key string
	// Value is what a Mapping binds: the winning value, expanded, or the
	// default of a Mapping if the key has no value or an empty one. A
	// reference to a secret key, as in postgres://u:${db.password}@host,
	// expands to "****".
	Value string
	// Origin is where Value comes from: the winning value's Origin or,
	// if IsDefault, the Mapping's, whose Source is "mapping:" followed by
	// its prefix and whose Location is the file and line of NewMapping.
	Origin Origin
	// IsDefault reports whether Value is the default of the Property.
	IsDefault bool
	// IsSecret reports whether the values are masked: the Property is
	// Secret, the name of the key contains "password", "secret", "token"
	// or "credential" in any case, or a value calls a secret Function.
	IsSecret bool
	// Functions names the Functions that computed Value, also through
	// references, in the order they were called: inner ones first, as in
	// [file base64] for ${base64::${file::/run/secrets/key}}. Explain
	// calls Functions that are no secret, with the results cached as for
	// Get; a secret Function, or one with a secret argument, is not called
	// and gives "****".
	Functions []string
	// Candidates holds every value for the key, as Candidates does, with
	// Raw replaced by "****" if IsSecret.
	Candidates []Value
	// Property is the definition of the key, as Describe and Properties
	// list it, nil if no Mapping reads the key. Its Key has <name> and <n>
	// where the key has the entries of maps and lists; its Env is that of
	// the key itself, such as DB_POOLS_MAIN_URL for db.pools.main.url.
	Property *Property
	// Err is set if the key has neither a value nor a default, or its value
	// cannot be expanded.
	Err error
}

Explanation tells where the value of a key comes from and, if a Mapping reads the key, what the key is: its Property. Secret values are already replaced by "****" in all of its fields, so it can be printed, logged or served as is; Get returns the real value.

func (Explanation) String

func (e Explanation) String() string

String shows the value, where it comes from and what it overrides: the winning value of a key without errors, else every candidate.

db.url = postgres://prod/app (env:DB_URL)
  overrides postgres://localhost/app (config/app.properties:3, profile dev)
  default postgres://localhost/test (db/db.go:12)

type Function

type Function struct {
	// Name is the name in ${name::arg}: letters, digits and '-', such as
	// "aes-gcm".
	Name string
	// IsSecret marks the results as secrets, as for a decrypted value or
	// the content of a secret file: Explain masks every key that calls the
	// Function, and a field that is no Secret but holds a result, also
	// through ${...} references, is a Load error. A result computed from a
	// secret argument, as in ${base64::${file::/run/secrets/key}}, is a
	// secret too.
	IsSecret bool
	// Call returns the result for arg, the text after "::" with its
	// expressions already expanded. origin tells where the expression is
	// written; it is the zero Origin for Eval. cfg is the Config being
	// read, e.g. to look up a key; Call must not expand values of cfg that
	// may contain expressions of its own name.
	//
	// The error must not contain a secret result.
	Call func(cfg *Config, arg string, origin Origin) (string, error)
	// Mapping declares the keys Call reads, nil if none. WithFunctions
	// registers it like a Mapping of WithMappings, so Describe, the
	// schema and the environment know the keys. Call still reads them
	// from cfg, as it may run before Mappings are bound.
	Mapping AnyMapping
}

A Function gives ${name::arg} expressions their meaning, such as ${env::HOME} or ${aes-gcm::AhB3...}. Register Functions with WithFunctions; gonf itself registers none.

type KeyMapper

type KeyMapper interface {
	MapKey(key string) string
}

KeyMapper is implemented by Sources whose names follow their own naming scheme, such as the environment. MapKey(key) is the name of key in that scheme, e.g. "DB_POOL_MAX_SIZE" for "db.pool.max-size". Describe and Explain show it as Property.Env; values are never looked up by it.

type Live

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

Live holds the current Config of Watch. It is safe for concurrent use.

func Watch

func Watch(ctx context.Context, opts ...WatchOption) (*Live, error)

Watch loads the configuration like Load and reloads it whenever a Source that implements Watcher reports a change, until ctx ends.

A reload is a complete Load with the same options: Sources, factories, profiles and all Mappings. If it succeeds, Live.Config returns the new Config; if it fails, the previous Config stays. Either way the function given with OnReload learns about it, and Watch logs it (see WithLogger). A Watcher that fails is reported the same way, as a SourceError; it is watched again after a delay that grows from one second to one minute, and every retry also reloads, since changes may have been missed.

If the first Load fails, Watch returns its error and does not watch.

func (*Live) Config

func (l *Live) Config() *Config

Config returns the current Config. Read it again for every unit of work, such as a request; a Config, and a struct bound from it, never changes.

type MappedSource

type MappedSource interface {
	Source
	LoadMapped(ctx context.Context, keys []string) (map[string]Value, error)
}

MappedSource is a Source whose names are not keys, such as environment variables. Load calls LoadMapped instead of Load, with the keys it knows: the keys of the Mappings given with WithMappings and the key of WithProfileKey. Other names are not reachable through such a Source. In a key, <name> stands for the name of a map entry and <n> for the index of a list element, as in db.pools.<name>.url; a list of single values comes as db.hosts and db.hosts[<n>]. LoadMapped returns its values under the keys their names match, with <name> and <n> filled in, such as db.pools.main.url for DB_POOLS_MAIN_URL, and "%profile.key" for a value of a profile. Names that match no key are left out.

type Mapping

type Mapping[T any] struct {
	// contains filtered or unexported fields
}

Mapping is the configuration of one module, bound to the keys under a prefix. A library declares it once:

var Mapping = gonf.NewMapping[Config]("db")

The application passes it to Load with WithMappings, which binds and validates it with all other Mappings, and reads it with Get.

Example
package main

import (
	"context"
	"fmt"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	// In a library: the configuration of the module and its Mapping.
	type DBConfig struct {
		URL  string
		Pool struct {
			MaxSize int `default:"10"`
		}
	}
	db := gonf.NewMapping[DBConfig]("db")

	// In the application: Load binds and validates every Mapping.
	cfg, err := gonf.Load(context.Background(),
		gonf.WithMappings(db),
		gonf.WithSources(memory.New(map[string]string{"db.url": "postgres://localhost/app"})),
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(db.Get(cfg).URL, db.Get(cfg).Pool.MaxSize)
}
Output:
postgres://localhost/app 10

func NewMapping

func NewMapping[T any](prefix string, opts ...MappingOption) *Mapping[T]

NewMapping returns a Mapping of T, which must be a struct, to the keys under prefix. Load binds it as follows.

Every exported field is bound to the key prefix.name. The name is the field name in kebab case (MaxSize becomes max-size) unless the field has a `cfg:"name"` tag; `cfg:"-"` skips the field. Values are read like Get, so profiles, ${...} expressions and environment variables (DB_POOL_MAX_SIZE) apply. An empty value counts as not set. A `desc:"..."` tag documents the field for Describe.

A field without a value uses its `default:"..."` tag, which is expanded like a value; an empty default leaves the zero value. A field with neither is an error, except for:

  • pointers, which stay nil, so *int or *Pool is optional
  • slices and maps, which stay empty

Field types:

  • string, bool, integers, floats; bool accepts true/false, 1/0, yes/no and on/off in any case; integers are decimal unless they have a prefix as in Go (0b101, 0o644, 0x1f) and may contain underscores (1_000); a leading zero as in 0644 is an error, as it reads as octal in Go but as decimal elsewhere
  • time.Duration in the format of time.ParseDuration, such as 5s or 1h30m
  • any type whose pointer implements encoding.TextUnmarshaler
  • any type with a converter given with WithConverter, which replaces the rules above
  • Secret[T] of any of these types
  • structs, bound to the keys under prefix.name; an embedded struct without a cfg tag is bound to the keys of its parent
  • slices, from a comma-separated value (a,b,c; \, for a literal comma) or from indexed keys such as name[0] and name[1].host; the comma-separated value wins if both exist
  • maps, whose keys are the segments after prefix.name, e.g. "team" for db.labels.team; a segment containing dots is quoted: db.servers."eu.west".host

Map entries and indexed elements are found among the keys of the Sources (see Keys); environment variables can override them but, except for indexed elements, not add new ones.

After its fields are bound without problems, a struct whose pointer implements

Validate() error

is validated; inner structs come first. A key under prefix that no field binds, such as a typo "db.pool.max-szie", is an error naming the closest known key; AllowUnknown turns this check off. A key that a bound value references, such as db.host in db.url=postgres://${db.host}/app, is known. The check is skipped for an empty prefix. An environment variable with a typo, such as DB_POOL_MAX_SIZ, matches no key and is left out (see MappedSource). Finally, the validator given with WithValidator checks the whole struct.

A field that is no Secret but whose value or default refers to a secret key, as in url=postgres://app:${db.password}@db/app, is a problem: the field would hold the secret and print it. Make the field a Secret too. Secret keys are those that Explain masks.

A field type or tag that Load cannot read, such as a func field or a default for a struct, is a problem even inside an optional struct or a list or map without entries; Load then reads no value for the Mapping.

All problems are collected; Load returns those of every Mapping together, each Mapping's as a *BindError.

Defaults come from the Source "mapping:" + prefix; their Location is the file and line of the call to NewMapping, relative to the working directory if below it.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	type Pool struct {
		MaxSize int           `default:"10"`
		Idle    time.Duration `cfg:"idle-timeout" default:"5m"`
	}
	type DB struct {
		URL      string
		Pool     Pool
		Replicas []string
		Timeout  *time.Duration
	}
	mapping := gonf.NewMapping[DB]("db")
	cfg, err := gonf.Load(context.Background(),
		gonf.WithMappings(mapping),
		gonf.WithSources(memory.New(map[string]string{
			"db.host":          "localhost",
			"db.url":           "postgres://${db.host}/app",
			"db.pool.max-size": "20",
			"db.replicas":      "replica-1,replica-2",
		})),
	)
	if err != nil {
		panic(err)
	}
	db := mapping.Get(cfg)
	fmt.Println(db.URL)
	fmt.Println(db.Pool.MaxSize, db.Pool.Idle, db.Replicas, db.Timeout)
}
Output:
postgres://localhost/app
20 5m0s [replica-1 replica-2] <nil>

func (*Mapping[T]) Get

func (m *Mapping[T]) Get(c *Config) T

Get returns the value bound when c was loaded. Its pointers, slices and maps are copies, so a caller may modify them without changing what other callers get; a type without them costs no copy. Values of types with a converter or UnmarshalText, such as *url.URL, are not copied and must not be modified. The copy is made on every call: read a Mapping once where it is used, not in a hot path.

Get panics if m was not passed to Load with WithMappings: that is a programming error, while every configuration error is reported by Load.

func (*Mapping[T]) Prefix

func (m *Mapping[T]) Prefix() string

Prefix returns the prefix of the Mapping's keys.

type MappingOption

type MappingOption func(*bindOptions)

MappingOption configures how Load binds a Mapping.

func AllowUnknown

func AllowUnknown() MappingOption

AllowUnknown turns off the check for unknown keys under the prefix, e.g. when several structs bind parts of the same prefix.

type NameReporter

type NameReporter interface {
	MappedSource
	LoadReport(ctx context.Context, keys, prefixes []string) (values map[string]Value, unknown []string, err error)
}

NameReporter is a MappedSource that also tells which of its names look meant for a Mapping but match no key. prefixes are the prefixes of the Mappings, such as "db"; the Source decides how they look in its naming scheme, e.g. DB_ in the environment, and returns the names that start like that and match none of keys. Load calls LoadReport instead of LoadMapped, and the names become Warnings.

type Option

type Option func(*loadOptions)

Option configures Load.

func WithConverter

func WithConverter[T any](convert func(s string) (T, error)) Option

WithConverter registers a function that converts a value into a T for Mappings, for a type that cannot implement encoding.TextUnmarshaler because it belongs to another package:

gonf.WithConverter(url.Parse) // fields of type *url.URL

A type that Load would read by its underlying kind needs one if its values are written differently, such as fs.FileMode, a uint32 written in octal:

gonf.WithConverter(func(s string) (fs.FileMode, error) {
	n, err := strconv.ParseUint(s, 8, 32)
	return fs.FileMode(n), err
})

It applies wherever a T is converted from a single value: fields of type T, *T and Secret[T], elements of slices and keys and values of maps. It replaces the built-in conversion of T, e.g. to read a bare number as seconds for time.Duration. A field of a pointer type T stays optional.

Only exactly T matches: a converter for *url.URL is not used for url.URL. Registering two converters for the same type is an error of Load.

Example
package main

import (
	"context"
	"fmt"
	"net/url"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	type API struct {
		Endpoint *url.URL
	}
	mapping := gonf.NewMapping[API]("api")
	cfg, err := gonf.Load(context.Background(),
		gonf.WithConverter(url.Parse),
		gonf.WithMappings(mapping),
		gonf.WithSources(memory.New(map[string]string{"api.endpoint": "https://example.com/v1"})),
	)
	if err != nil {
		panic(err)
	}
	api := mapping.Get(cfg)
	fmt.Println(api.Endpoint.Host, api.Endpoint.Path)
}
Output:
example.com /v1

func WithFactories

func WithFactories(factories ...SourceFactory) Option

WithFactories adds SourceFactories and registers their Mappings. They run after the Sources of WithSources and WithProfileSources have been loaded; their Sources count as registered after those.

func WithFunctions

func WithFunctions(fns ...Function) Option

WithFunctions registers Functions for ${name::arg} expressions and their Mappings. Two Functions with the same name are a Load error.

The results are cached per Load, keyed by name and expanded argument: within one Config, ${uuid::} gives the same value everywhere, also in Explain and Eval, and every Watch reload calls the Function anew. Only results are cached, not errors. A Function that must return the same result for the whole process caches itself.

func WithMappings

func WithMappings(mappings ...AnyMapping) Option

WithMappings registers Mappings. Load binds and validates all of them and reports the problems of all together. Keys under a prefix are unknown only if no Mapping binds them, so Mappings may share a prefix.

Default tags stay with the struct: they are not values of the Config, so Get does not see them. A value that needs a fallback names it itself, as in ${db.pool.max-size:10}.

SourceFactories run before the Mappings are bound and cannot Get them.

func WithProfileKey

func WithProfileKey(key string) Option

WithProfileKey activates the profiles listed in the value of key, a comma-separated list such as "dev,local", unless WithProfiles names any. The value is read from the Sources given with WithSources, without profiles applied, and expanded like Get. Sources created by factories cannot change it. If passed more than once, the last key is used.

func WithProfileSources

func WithProfileSources(sources func(profile string) []Source) Option

WithProfileSources adds Sources for every active profile, such as the file app-<profile>.yaml. Load calls sources once per active profile, in the order of the profiles, after the active profiles are settled, and loads the Sources it returns together with those of WithSources, so a SourceFactory sees them. They count as registered after the Sources of WithSources. gonf closes them like the Sources of a factory.

func WithProfiles

func WithProfiles(names ...string) Option

WithProfiles activates profiles. Can be passed multiple times; of several active profiles the last one wins. Names are trimmed and empty names are ignored, so the result of strings.Split(os.Getenv("APP_PROFILE"), ",") can be passed as is. A name must not contain '.', ',' or whitespace.

func WithSecretWords

func WithSecretWords(words ...string) Option

WithSecretWords adds words to those that mark a key as secret by its name: "password", "secret", "token" and "credential". A key that contains one of them, in any case, is masked by Explain and shown as secret by Describe, e.g. WithSecretWords("passphrase", "private-key"). It can be passed multiple times; empty words are ignored.

func WithSources

func WithSources(srcs ...Source) Option

WithSources adds Sources. Can be passed multiple times; the order of registration breaks ties between equal ordinals (later wins).

func WithValidator

func WithValidator(validate func(v any) error) Option

WithValidator sets a function that validates every struct bound by a Mapping, such as Struct of github.com/go-playground/validator. It gets a pointer to the struct after its own Validate methods succeeded.

type OptionalSource

type OptionalSource interface {
	IsOptional() bool
	IsMissing() bool
}

OptionalSource is implemented by Sources that may have nothing to read, such as a file made source.Optional. IsMissing reports whether the last Load found nothing; it is only asked right after Load.

type Origin

type Origin struct {
	// Source is the name of the Source, e.g. "env:" or
	// "file:/etc/app/app.properties".
	Source string
	// Ordinal is the priority of the Source. Higher wins.
	Ordinal int
	// Profile is the profile the value belongs to, e.g. "dev" for a value
	// from a "%dev.db.url" key. Empty for a base value.
	Profile string
	// Location is an optional, more precise position such as
	// "file:/etc/app/app.properties:12".
	Location string
}

Origin describes where a Value came from.

type Problem

type Problem struct {
	Key string
	// Origin is where the offending value came from; zero if the key has no
	// value or the default is invalid.
	Origin Origin
	// Err matches ErrNotFound if a required value is missing.
	Err error
}

Problem is one key that Load could not bind.

func (*Problem) Error

func (p *Problem) Error() string

Error names the key, the problem and, if known, where the value came from.

func (*Problem) Unwrap

func (p *Problem) Unwrap() error

Unwrap returns Err.

type ProfileSource

type ProfileSource interface {
	Profile() string
}

ProfileSource is implemented by Sources whose keys all belong to one profile, such as the files of source.WithProfile.

type Property

type Property struct {
	// Key is the key, with <name> for the key of a map entry and <n> for
	// the index of a list element: db.pools.<name>.url, db.hosts[<n>].port.
	Key string `json:"key"`
	// Env is the name of the key in the first Source that is a KeyMapper,
	// such as DB_POOL_MAX_SIZE for env.New; empty if there is no such
	// Source or the key contains <name> or <n>.
	Env string `json:"env,omitempty"`
	// Type is the Go type of the value; a Secret[T] is described as T with
	// Secret set.
	Type string `json:"type"`
	// Default is the default tag, not expanded, nil without one; masked if
	// Secret.
	Default *string `json:"default,omitempty"`
	// Required reports whether Load fails without a value for the key. Inside
	// an optional struct (a pointer), a map entry or a list element, it
	// applies only if that exists.
	Required bool `json:"required"`
	// Secret reports whether the value is a Secret or the key is named like
	// one, such as db.password; Explain masks it.
	Secret bool `json:"secret,omitempty"`
	// Doc is the desc tag of the field.
	Doc string `json:"doc,omitempty"`
	// Mapping is the prefix of the Mapping that reads the key, Location the
	// file and line of its NewMapping.
	Mapping  string `json:"mapping"`
	Location string `json:"location,omitempty"`
	// IsUnknownAllowed reports whether the Mapping was made with
	// AllowUnknown, so keys next to this one are not an error.
	IsUnknownAllowed bool `json:"unknownAllowed,omitempty"`
}

Property describes one key that a Mapping reads: its definition, from the struct alone, for documentation such as the configuration reference of an application and next to the value in an Explanation.

func Describe

func Describe(opts ...Option) ([]Property, error)

Describe returns the Properties of the Mappings given with WithMappings, in the order of the Mappings and their fields. It takes the same options as Load, so an application can document its configuration with the options it loads it with:

opts := []gonf.Option{gonf.WithSources(env.New()), gonf.WithMappings(db.Mapping)}
if *configDoc {
	props, err := gonf.Describe(opts...)
	...
}
cfg, err := gonf.Load(ctx, opts...)

Describe reads no Source and runs no SourceFactory, so it works without the values, e.g. in a build. It uses WithConverter to tell single values from structs and the Sources only for Property.Env. Describe and Load read a struct the same way, so a field type Load cannot read is the same *BindError here as in Load. Of two Mappings with the same key, the first describes it.

If several keys have the same Env, such as db.max-size and db.max.size as DB_MAX_SIZE, Describe fails with an error that wraps ErrNameConflict for each such name; Load reports them as Warnings, since an application that never sets those keys through the environment works.

A field documents itself with a desc tag:

MaxSize int `default:"10" desc:"Maximum number of open connections."`
Example
package main

import (
	"log"
	"os"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source/env"
)

func main() {
	type DB struct {
		URL      string              `desc:"Where the database runs."`
		Password gonf.Secret[string] `desc:"Password of the user."`
		Pool     struct {
			MaxSize int `default:"10" desc:"Maximum number of open connections."`
		}
	}
	props, err := gonf.Describe(
		gonf.WithSources(env.New()),
		gonf.WithMappings(gonf.NewMapping[DB]("db")),
	)
	if err != nil {
		log.Fatal(err)
	}
	if err := gonf.WriteMarkdown(os.Stdout, props); err != nil {
		log.Fatal(err)
	}
}
Output:
| Key | Environment variable | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `db.url` | `DB_URL` | `string` | required | Where the database runs. |
| `db.password` | `DB_PASSWORD` | `string` (secret) | required | Password of the user. |
| `db.pool.max-size` | `DB_POOL_MAX_SIZE` | `int` | `10` | Maximum number of open connections. |

type Secret

type Secret[T any] struct {
	// contains filtered or unexported fields
}

Secret holds a configuration value that must not show up in output:

type DB struct {
	User     string
	Password gonf.Secret[string]
}

Load converts the value as for a field of type T, which must be a type Load converts from a single value, such as string, int or a type with UnmarshalText. An invalid value is reported without the value itself. Use *Secret[T] for an optional secret.

fmt, encoding/json and other encodings using MarshalText, and log/slog print "****"; Value returns the value. Keys bound to a Secret are masked in Explain. A field that refers to a secret key with ${...} must be a Secret too; Load reports it otherwise.

Example
package main

import (
	"context"
	"fmt"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	type DBConfig struct {
		User     string
		Password gonf.Secret[string]
	}
	mapping := gonf.NewMapping[DBConfig]("db")
	cfg, err := gonf.Load(context.Background(),
		gonf.WithMappings(mapping),
		gonf.WithSources(memory.New(map[string]string{
			"db.user":     "app",
			"db.password": "hunter2",
		})),
	)
	if err != nil {
		panic(err)
	}
	db := mapping.Get(cfg)
	fmt.Printf("%+v\n", db)
	fmt.Println(db.Password.Value())
}
Output:
{User:app Password:****}
hunter2

func NewSecret

func NewSecret[T any](v T) Secret[T]

NewSecret returns a Secret holding v, e.g. for tests.

func (Secret[T]) Format

func (s Secret[T]) Format(f fmt.State, _ rune)

Format prints "****" for every verb, also %#v.

func (Secret[T]) LogValue

func (s Secret[T]) LogValue() slog.Value

LogValue returns "****" for log/slog.

func (Secret[T]) MarshalText

func (s Secret[T]) MarshalText() ([]byte, error)

MarshalText returns "****", so encodings such as JSON do not reveal the value.

func (Secret[T]) String

func (s Secret[T]) String() string

String returns "****".

func (Secret[T]) Value

func (s Secret[T]) Value() T

Value returns the secret value.

type Source

type Source interface {
	Name() string
	Ordinal() int
	Load(ctx context.Context) (map[string]Value, error)
}

Source delivers configuration values.

Name identifies the Source and must start with a scheme naming the kind of origin, e.g. "file:/etc/app.properties", "env:" or "k8s:configmap/my-namespace/app-config" (see Scheme).

Load returns flat keys (e.g. "db.pool.max-size"). A key prefixed with "%profile." (e.g. "%dev.db.url") belongs to that profile. Sources only need to set Value.Raw and optionally Value.Origin.Location; the other Origin fields are filled in by gonf.

type SourceError

type SourceError struct {
	// Source is the name of the failed Source.
	Source string
	// Err is the error returned by Source.Load, ErrInvalidSourceName, an
	// error about an invalid profile key, or the error returned by
	// Watcher.Watch or by Close.
	Err error
}

SourceError reports that a Source failed to load.

func (*SourceError) Error

func (e *SourceError) Error() string

func (*SourceError) Unwrap

func (e *SourceError) Unwrap() error

type SourceFactory

type SourceFactory interface {
	// Mapping returns the Mapping the factory reads its configuration
	// from.
	Mapping() AnyMapping
	// contains filtered or unexported methods
}

A SourceFactory creates Sources that need configuration themselves, e.g. a Vault Source whose address is configured in a file. Create one with NewFactory.

func NewFactory

func NewFactory[T any](m *Mapping[T], create func(ctx context.Context, v T) ([]Source, error)) SourceFactory

NewFactory returns a SourceFactory that creates Sources from the configuration in m. Load binds m before the factory runs, from the Sources of WithSources and WithProfileSources, and passes the value to create. m is registered like a Mapping of WithMappings: Describe, Explain, the schema and the environment know its keys.

The Sources a factory creates must not set a key under the prefix of the Mapping of any factory, since that configuration was read before they were loaded: it is a Load error. NewFactory panics if m is nil or has no prefix, or if create is nil.

A factory with nothing to contribute returns no Sources. Errors should say which factory failed.

The Sources a factory returns belong to gonf. If one implements io.Closer, gonf closes it when it is no longer needed: Load right after loading it, Watch when a reload replaces it or fails, and when watching stops. Load ignores errors from Close, Watch logs them. A factory may return a Source it returned before; Watch keeps it open while it is in use. Only Watch benefits from that, since Load closes every Source it got.

Separate calls of Load or Watch may run a factory concurrently, so state it keeps between calls must be safe for concurrent use. Within one Watch a factory runs on one goroutine at a time.

Example
package main

import (
	"context"
	"fmt"

	"github.com/efuturetoday/gonf"
	"github.com/efuturetoday/gonf/source"
	"github.com/efuturetoday/gonf/source/memory"
)

func main() {
	// A factory creates Sources that need configuration themselves, here a
	// stand-in for a Vault Source whose address comes from a file. Its
	// configuration is a Mapping like any other: typed, checked and
	// documented.
	type Vault struct {
		Addr string `desc:"Address of the Vault."`
	}
	vault := gonf.NewFactory(gonf.NewMapping[Vault]("vault"),
		func(_ context.Context, v Vault) ([]gonf.Source, error) {
			return []gonf.Source{memory.New(
				map[string]string{"db.password": "s3cret"},
				source.WithName("vault:"+v.Addr),
			)}, nil
		})
	cfg, err := gonf.Load(context.Background(),
		gonf.WithSources(memory.New(map[string]string{"vault.addr": "https://vault:8200"})),
		gonf.WithFactories(vault),
	)
	if err != nil {
		panic(err)
	}
	v, _ := cfg.Lookup("db.password")
	fmt.Println(v.Origin.Source)
}
Output:
vault:https://vault:8200

type SourceInfo

type SourceInfo struct {
	Name    string `json:"name"`
	Ordinal int    `json:"ordinal"`
	// Profile is the profile every key of the Source belongs to (see
	// ProfileSource), empty if the Source is not bound to one.
	Profile string `json:"profile,omitempty"`
	// Keys is the number of keys the Source delivered, profile keys
	// included.
	Keys int `json:"keys"`
	// IsOptional reports that a missing document is not an error (see
	// OptionalSource), IsMissing that the document was missing: the Source
	// delivered nothing.
	IsOptional bool `json:"optional,omitempty"`
	IsMissing  bool `json:"missing,omitempty"`
}

SourceInfo describes a loaded Source, see Config.Sources.

type Value

type Value struct {
	// Raw is the unconverted value.
	Raw    string
	Origin Origin
}

Value is a single raw configuration value as delivered by one Source.

All values are strings, independent of where they come from. Conversion to typed values happens only when reading, so a value from a file and an override from the environment always go through the same path.

type VerbatimSource

type VerbatimSource interface {
	IsVerbatim() bool
}

VerbatimSource is implemented by Sources whose values are text, never expressions, such as values others may write. If IsVerbatim reports true, Load escapes every value (see Escape), so ${file::...} or ${env::...} in it stays as written and calls no Function. Lookup and Explain show the escaped value, Get the value as the Source delivered it.

type Warning

type Warning struct {
	Kind WarningKind `json:"kind"`
	// Source is the name of the Source concerned.
	Source string `json:"source,omitempty"`
	// Name is the name in the Source: the unknown one, or the one the Keys
	// share.
	Name string `json:"name"`
	// Keys are the conflicting keys, sorted; empty for WarnUnknownName.
	Keys []string `json:"keys,omitempty"`
	// Message is the warning in words, with a suggestion if one is close.
	Message string `json:"message"`
}

Warning is something Load noticed that does not make the configuration invalid; see Config.Warnings.

func (Warning) String

func (w Warning) String() string

String returns the Message, with the Source in front.

type WarningKind

type WarningKind string

WarningKind tells what a Warning is about.

const (
	// WarnUnknownName: a Source has a name under the prefix of a Mapping
	// that matches no key, such as DB_PORT when only DB_URL is read.
	// Typically a typo, but also what a platform adds, such as the
	// variables of a Kubernetes service link, so it is no error.
	WarnUnknownName WarningKind = "unknown-name"
	// WarnNameConflict: several keys have the same name in a Source, such
	// as db.max-size and db.max.size as DB_MAX_SIZE, so a value cannot
	// tell which one it is for.
	WarnNameConflict WarningKind = "name-conflict"
)

type WatchOption

type WatchOption interface {
	// contains filtered or unexported methods
}

A WatchOption configures Watch. Every Option is one, so Watch takes everything Load takes; OnReload and WithLogger are WatchOptions only and do not compile as options of Load.

func OnReload

func OnReload(fn func(cfg *Config, err error)) WatchOption

OnReload makes Watch call fn after every reload: with the new Config, or with the error that kept the previous one. fn is never called concurrently, and no reload starts while it runs.

func WithLogger

func WithLogger(l *slog.Logger) WatchOption

WithLogger sets the logger Watch reports to: reloads at level Info; failed reloads, failed Watchers and Sources that failed to close at level Warn. Without it Watch uses slog.Default. Load does not log; it returns its errors.

type Watcher

type Watcher interface {
	Watch(ctx context.Context, changed func()) error
}

Watcher is implemented by Sources that notice when their values change, such as a file that is edited or a key store that pushes updates. Watch calls changed whenever the values may differ from what Load last returned; changed is safe for concurrent use and never blocks. Watch blocks until ctx ends and returns an error only if it can no longer watch.

Directories

Path Synopsis
Package boot loads configuration by convention, from files in known places, a .env file and the environment, with profiles.
Package boot loads configuration by convention, from files in known places, a .env file and the environment, with profiles.
cmd
gonf module
examples
basic command
Command basic shows layered sources (defaults < files < env), profiles and expressions.
Command basic shows layered sources (defaults < files < env), profiles and expressions.
boot command
Command boot shows loading by convention: embedded defaults, config/, .env and environment variables, with the profile from GONF_PROFILE.
Command boot shows loading by convention: embedded defaults, config/, .env and environment variables, with the profile from GONF_PROFILE.
library-module command
Command library-module shows a library that brings its own configuration (package db) and an application that loads it and prints its configuration reference.
Command library-module shows a library that brings its own configuration (package db) and an application that loads it and prints its configuration reference.
library-module/db
Package db stands for a library that brings its own configuration: it declares the keys it reads under "db", with defaults and descriptions, and the application only registers the Mapping.
Package db stands for a library that brings its own configuration: it declares the keys it reads under "db", with defaults and descriptions, and the application only registers the Mapping.
quickstart command
Command quickstart is the example of the README.
Command quickstart is the example of the README.
reload command
Command reload shows a configuration that stays current.
Command reload shows a configuration that stays current.
format
dotenv
Package dotenv provides the .env format for gonf.
Package dotenv provides the .env format for gonf.
json
Package json provides the JSON format for gonf.
Package json provides the JSON format for gonf.
properties
Package properties provides the .properties format for gonf.
Package properties provides the .properties format for gonf.
yaml module
function
base64
Package base64 provides the gonf.Functions base64 and base64-decode, with the standard encoding of RFC 4648, padded:
Package base64 provides the gonf.Functions base64 and base64-decode, with the standard encoding of RFC 4648, padded:
file
Package file provides the gonf.Function file, which reads a file, such as a secret mounted by a container platform:
Package file provides the gonf.Function file, which reads a file, such as a secret mounted by a container platform:
git
Package git provides the gonf.Function git, with what git knows of a directory, for values such as the tag of an image:
Package git provides the gonf.Function git, with what git knows of a directory, for values such as the tag of an image:
slug
Package slug provides the gonf.Function slug, which makes its argument fit for a name: lower case letters, digits and '-', at most 63 long, as a tag of an image, a name in Kubernetes or a label of DNS takes it:
Package slug provides the gonf.Function slug, which makes its argument fit for a name: lower case letters, digits and '-', at most 63 long, as a tag of an image, a name in Kubernetes or a label of DNS takes it:
uuid
Package uuid provides the gonf.Function uuid, which returns a random UUID (version 4):
Package uuid provides the gonf.Function uuid, which returns a random UUID (version 4):
Package schema turns the Properties of gonf.Describe into a JSON Schema (draft 2020-12) of the configuration, so that editors offer completion, type checks and descriptions for YAML and JSON configuration files.
Package schema turns the Properties of gonf.Describe into a JSON Schema (draft 2020-12) of the configuration, so that editors offer completion, type checks and descriptions for YAML and JSON configuration files.
secret
aesgcm
Package aesgcm decrypts configuration values encrypted with AES-256 in GCM mode, written as ${aes-gcm::value}:
Package aesgcm decrypts configuration values encrypted with AES-256 in GCM mode, written as ${aes-gcm::value}:
Package source is the common base for gonf Sources.
Package source is the common base for gonf Sources.
dir
Package dir provides a gonf Source reading a directory with one file per key, as Kubernetes mounts a Secret or a ConfigMap: the file name is the key, the file content the value.
Package dir provides a gonf Source reading a directory with one file per key, as Kubernetes mounts a Secret or a ConfigMap: the file name is the key, the file content the value.
env
Package env provides the process environment as a gonf Source (New), the environment variable naming scheme (MapKey) and the matching of variable names against keys (Match), which .env files use too (see format/dotenv).
Package env provides the process environment as a gonf Source (New), the environment variable naming scheme (MapKey) and the matching of variable names against keys (Match), which .env files use too (see format/dotenv).
file
Package file provides gonf Sources reading config documents from the file system or from an fs.FS such as embed.FS.
Package file provides gonf Sources reading config documents from the file system or from an fs.FS such as embed.FS.
flagsource
Package flagsource provides command-line flags as a gonf Source (New) and defines the flags of an application's Mappings (Define).
Package flagsource provides command-line flags as a gonf Source (New) and defines the flags of an application's Mappings (Define).
memory
Package memory provides gonf Sources backed by a map, for defaults and tests.
Package memory provides gonf Sources backed by a map, for defaults and tests.
sourcetest
Package sourcetest checks that a gonf.Source keeps the contract gonf relies on.
Package sourcetest checks that a gonf.Source keeps the contract gonf relies on.

Jump to

Keyboard shortcuts

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