config

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 19 Imported by: 0

README

gas/config

Test Go Reference Go Version License

Part of the Gas monorepo · Documentation · All modules

Configuration for the Gas framework. Loads from environment variables, JSON, .env files, and AWS Secrets Manager, and binds the result to Go structs with validation.

Implements gas.ConfigProvider.

go get github.com/gasmod/gas/config
cfg := config.New(config.WithProvider(config.NewEnvProvider(config.WithEnvPrefix("APP_"))))
if err := cfg.Load(); err != nil { log.Fatal(err) }

gas.WithServiceInstance[gas.ConfigProvider](cfg),

Config needs nothing from the container: it is built and loaded before the app, so a bad configuration fails before anything else starts.

Package Provides
config Config; environment, JSON, and .env providers; environment detection extension
config/secretsmanager AWS Secrets Manager
config/configtest Mock, a real-backed fake seeded with known values, and a static provider

Documentation

The full documentation is on the docs site. This README is deliberately a signpost: keeping a second copy here is how the docs drifted before.

License

MIT

Documentation

Overview

Package config loads an app's configuration from providers, such as the environment, `.env` and JSON files, and AWS Secrets Manager, merges it into one tree of values, and binds that tree into structs.

Usage

Build a Config with its providers, load it, and bind a struct:

cfg := config.New(
	config.WithProvider(config.NewJSONProvider(config.WithJSONFilePath("config.json"))),
	config.WithProvider(config.NewEnvProvider(config.WithEnvPrefix("APP_"))),
)
if err := cfg.Load(); err != nil {
	return err
}

type AppConfig struct {
	Database struct {
		Host string `validate:"required"`
		Port int
	}
}
var app AppConfig
app.Database.Port = 5432 // kept unless the configuration sets it
if err := cfg.Bind(&app); err != nil {
	return err
}

With `APP_DATABASE__HOST=db` in the environment, app.Database.Host is `db`, and cfg.Get("database.host") returns it too.

A Config holds nothing until it is loaded. Without a provider, New adds an EnvProvider with the default separator and no prefix, which fails to load with ErrEnvPrefixRequired.

*Config implements ConfigProvider, the interface services read configuration through.

Providers

A Provider returns a map of values each time it loads. The package has three:

Package secretsmanager reads AWS Secrets Manager.

Environment variables

EnvProvider reads the process environment, and turns each variable's name into a key:

  • `__` separates the levels of a name, so `DATABASE__HOST` is the key `host` under `database`. WithEnvSeparator changes it, and an empty separator keeps every name one level.
  • Names are lowercased.
  • A name with an empty level, such as `A____B` with `__`, is left out.

A provider needs a prefix: without one, Load fails with ErrEnvPrefixRequired and reads nothing. WithEnvPrefix keeps only the names that start with the prefix, without regard to case, and removes it. The separator is not added to the prefix, so `APP_` turns `APP_HOST` into `host`, where `APP` would turn it into `_host`.

WithoutEnvPrefix opts in to loading every variable that is not left out, such as another tool's API key or a `DATABASE_URL`. Never log Config.Values with it.

Variables that describe the user, shell or session rather than the app, and can leak secrets or change what the process runs, are always left out: `PATH`, `HOME`, `USER`, `SHELL`, `LD_PRELOAD`, session variables such as `SSH_AUTH_SOCK` and `SUDO_USER`, `GITHUB_TOKEN`, `CI` and others.

Two names that become the same key are an error. That covers names such as `Foo` and `FOO`, and names where one needs the other's key as a map, such as `A` and `A__B`.

The .env file

DotEnvProvider reads a `.env` file, and turns its names into keys as EnvProvider does:

The format is small and strict, and anything outside it is an error:

# a comment
DB__HOST=localhost
DB__PORT = 5432            # spaces around "=" are allowed
DB__NAME="app db"          # quotes keep spaces and "#", and may span lines
DB__URL=postgres://${DB__HOST}:${DB__PORT}/app
DB__PASSWORD='p@ss${not-a-ref}'

Its rules:

  • A name is `[A-Za-z_][A-Za-z0-9_]*`, defined once, and not differing from another only in case. There is no `export`.
  • An unquoted value ends at a space, tab or `#`.
  • Nothing is escaped, so a backslash is text and a double-quoted value cannot hold `"`.
  • `${NAME}` in an unquoted or double-quoted value is the value of NAME in the same file, never the process environment. A single-quoted value is not expanded.
  • A reference to a name the file does not define, or a cycle, is an error.
  • The file must be valid UTF-8.

With WithDotEnvFileAppendToOSEnv, each load also copies the file's variables into the process environment, only once the whole file has loaded. The unsafe variables listed under Environment variables are not copied. A name left out of the configuration for an empty level is still copied.

The file sets the application environment as `GAS_ENV`, which becomes the key `gas_env`, or as `GASENV`, the key `gasenv` (see Resolving the environment). Either loses to the variable `GAS_ENV` in the process environment.

JSON files

JSONProvider reads a JSON file, whose path WithJSONFilePath sets; it has no default. The file must hold an object.

Its values have the types encoding/json gives them, except numbers:

  • An object is a map[string]any, a list a []any, and null nil.
  • Numbers keep their digits. An integer is an int64, or a uint64 when it is too large for one. Any other number, such as `1.5`, is a float64.
  • A number too large for a float64, such as `1e400`, is an error.

File access

The JSON and `.env` providers read from the working directory. A path is relative to it or absolute, and the file must:

  • lie inside the working directory, symlinks included;
  • be a regular file;
  • be at most 1 MiB.

A symlink on the path must be relative: an absolute one is refused, even when its target lies inside the working directory.

WithJSONFileFS and WithDotEnvFileFS read from any fs.FS instead, such as an embed.FS, without those checks. A path then follows that file system's rules, which for an embed.FS means slash-separated and unrooted, with no `.` or `..` element. A nil fs.FS reads from the working directory.

Writing a provider

A provider implements Provider. One that should take the load's context also implements ContextProvider, and the Config calls its LoadContext instead of Load.

The Config keeps a copy of the map a provider returns, so the provider may keep and change it. The provider's Name names it in errors.

Loading

Config.Load, or Config.LoadWithContext, runs these steps, in order:

  1. It runs each extension's PreLoad.
  2. It loads every provider, in the order they were added.
  3. It merges their values over the configuration, in that order (see Merging).
  4. It runs each extension's PostLoad.

Every provider loads before anything is merged, outside the lock, so a reader never sees part of a load.

The first error stops the load:

  • A failing PreLoad stops it before any provider loads.
  • A failing provider merges none of the providers' values, though what the extensions' PreLoad stored stays.
  • A failing PostLoad stops it after the values are merged, and they stay.

A load merges over what the configuration holds and never removes a key. Loading again loads every provider again:

  • A key that a provider no longer returns keeps its value.
  • A value stored with Set keeps its value unless a provider sets that key.

Config.LoadProvider loads one more provider, merges its values over the configuration, and adds it to the providers that later loads load. A provider that fails to load is not added. Extensions do not run.

Merging

Each provider's keys are trimmed and lowercased before it is merged, at every depth of its maps and of the lists ([]any) in them. A slice of another type, such as []map[string]any, keeps the keys of its maps.

Two keys of one provider that become the same, such as `Host` and `host`, are an error. `Host` in one provider and `host` in a later one are not, and the later one wins.

Where the configuration and a provider hold a map under one key, the maps are merged key by key. Anywhere else the provider's value replaces what the configuration holds:

  • A value replaces a map, and a map replaces a value.
  • A list replaces a list as a whole.
  • nil replaces anything.

Keys

Config.Get, Config.Find, Config.Set and Config.SetDefault take a key with a dot between levels, so `database.host` is the key `host` in the map under `database`. Each level is trimmed and lowercased, so `Database.HOST` is the same key.

A key that is empty, or has a level that is empty once trimmed, such as `a..b` or `a. .b`, is no key. Get and Find find nothing at it, and Set and SetDefault return an error wrapping ErrInvalidKey.

A key in the tree that holds a dot, such as one a JSON file sets as `{"database.host": "db"}`, cannot be reached, as the dot splits it.

Reading

Get returns the value at a key, or nil when it holds none. Config.Find also reports whether the key holds a value, which tells a key holding nil from a missing one. Config.Values returns the whole tree.

All three return a copy: maps, slices and pointers are copied at every depth, so changing the result does not change the configuration. A struct is copied the way Go copies it, so a map inside one is shared.

A *Config prints, with fmt and any verb, and logs, with log/slog, only how many providers, extensions and top-level keys it has, such as `config.Config{providers: 1, extensions: 1, keys: 3}`, never a value. What Values, Get and Find return is the values themselves, secrets included: never log or print them.

Writing

Set stores a value at a key, replacing what it holds, and adds the maps missing on its path. A level on the path that holds a value that is not a map blocks it: Set returns an error wrapping ErrKeyPathBlocked and changes nothing.

Config.SetDefault stores a value only at a key that holds none. A key holding nil holds a value. A key under a level that holds a value is left alone too, without an error.

Both store a copy, made as Get makes one:

  • The keys of a map in it are trimmed and lowercased at every depth, like a provider's, so every key in it can be reached.
  • A map of any key type becomes a map[string]any.
  • Two keys of one map that become the same are an error wrapping ErrKeyConflict, and nothing is stored.

Defaults

Config.SetDefaults takes a map[string]any, a pointer to one, a struct or a pointer to one, and adds the keys the configuration does not hold. A struct's fields are named as Bind names them, under Binding.

  • Its keys are trimmed and lowercased like a provider's. Two that become the same are an error wrapping ErrKeyConflict.
  • Where both hold a map under one key, the maps are merged the same way.
  • Any other key the configuration holds keeps its value.

Defaults set before a load are a base that the providers load over.

Binding

Config.Bind fills the struct a pointer points to from the configuration, then validates it (see Validation):

  • Each key that matches a field sets that field.
  • A field without a key keeps its value, so a struct filled with defaults keeps them.
  • A key without a field is ignored.

Fields are named as encoding/json names them: by the name in a json tag, or else the Go name. A field tagged `json:"-"` or unexported is left out. The fields of an embedded struct bind at the level of the struct that embeds it.

A key matches a field with exactly its name, or else without regard to case. Two keys that match one field are an error.

A value of a type that can be assigned to the field is copied into it. Anything else is converted to the field's type:

  • A struct field takes a map, bound into it by the same rules.
  • A map field takes a map with string keys; a slice field takes a list, or a string split on `,` with each element trimmed. Either replaces the field's value as a whole.
  • An array field takes a list no longer than the array, which replaces it as a whole; elements past the end of the list are zero.
  • A bool, integer or float field takes a value of that kind, or a string that parses as one, such as `8080`. A number that does not fit the field's type is an error. A float fits an integer field only when it is a whole number, so 8080.0 binds as 8080, while 8080.7, NaN and an infinity are errors; the string `8080.0` is an error too.
  • A string field takes a string, and a bool or number formatted with fmt.Sprint, except that a float is written without an exponent, so 1234567.0 is `1234567`.
  • A time.Duration field takes a string that time.ParseDuration accepts, so it needs a unit: `30s` works, `30` is an error, and `0` is zero.
  • nil sets the field to its zero value, and a pointer field is allocated when it is nil.

Validation

After filling the struct, Bind validates it with a Validator. By default that is *validator.Validate from github.com/go-playground/validator/v10, which reads `validate` struct tags. WithValidator sets another, such as one with custom tags registered.

A struct that fails to fill is not validated, and fields set before the error keep their new values.

The application environment

EnvExtension resolves the environment the app runs in, such as development or production, during each load, and stores it at the key `GasEnv`.

New adds an EnvExtension with the default options, which runs before the extensions WithExtension adds, so every Config resolves the environment unless it is told not to:

  • An EnvExtension given to WithExtension takes the default's place, so one Config never has two.
  • WithoutEnvExtension leaves the default out, so the configuration neither reads nor checks `GAS_ENV`, and holds no `GasEnv` unless a provider sets it.

An app reads the environment by binding a field of type Environment, which is gas.Environment, from that key, as gas.Config.Env does. A field named `Env` needs the tag, as its own name is the key `env`. With WithConfigKey set to `env`, it binds without one:

type AppConfig struct {
	Env config.Environment `json:"gasenv"`
}

The extension also reports the environment itself. The default one is not reachable, so an app that asks it gives New its own:

envExt := config.NewEnvExtension()
cfg := config.New(config.WithExtension(envExt))
if err := cfg.Load(); err != nil {
	return err
}
if envExt.IsProduction() {
	// production-only setup
}

EnvExtension.Current returns the environment the last load resolved, or the empty Environment before the first load.

Resolving the environment

The environment is the first of these:

  1. The value of the variable `GAS_ENV`, unless it is unset or empty.
  2. Else the value at the key, `gasenv`, such as `GASENV` in a `.env` file sets.
  3. Else the value at `gas_env`, the key that EnvProvider and DotEnvProvider make of the variable's name, such as `GAS_ENV` in a `.env` file sets. The empty string there counts as unset, as it does for the variable.
  4. Else the fallback, development.

So the process environment wins over a file here as it does for every other setting, and a `.env` file may say `GAS_ENV` or `GASENV`. A provider that sets both keys to different values gets the one at `gasenv`. An unprefixed EnvProvider stores the variable at `gas_env` too, which agrees with it. The extension leaves `gas_env` in the configuration, as a load leaves every key a provider sets.

The allowed values are development, testing, staging and production, compared with their case. The fallback is always allowed.

A value that is not allowed fails the load with an error wrapping ErrEnvironmentNotAllowed, so a typo such as `prod` stops the app rather than running it as development:

  • From the variable, PreLoad fails.
  • From a provider, or a key holding anything but a string, PostLoad fails.

Every source that holds a value is checked on every load, even one that an earlier source wins over. So a typo in any of them fails the load though its value would not be used. The error names the variable or key and the allowed values, not the value.

Options change these defaults:

  • WithEnvVarName changes the variable, and with it the key made of its name, such as `app_env` for `APP_ENV`.
  • WithAllowedEnvs changes the allowed values.
  • WithDefault changes the fallback.
  • WithConfigKey changes the key. With another key, the environment is stored at `GasEnv` too.

An App checks the environment too. App.Start accepts only the environments gas.WithAllowedEnvironments sets, by default the four above, so an environment that WithAllowedEnvs or WithDefault adds, such as `local`, loads but fails Start with an error wrapping gas.ErrInvalidConfig:

gas: invalid config: gasenv must be one of development, testing, staging, production

Give both the same environments:

envs := []config.Environment{"local", config.EnvStaging, config.EnvProduction}
envExt := config.NewEnvExtension(
	config.WithAllowedEnvs(envs...),
	config.WithDefault("local"),
)
cfg := config.New(
	config.WithProvider(config.NewEnvProvider(config.WithEnvPrefix("APP_"))),
	config.WithExtension(envExt),
)
if err := cfg.Load(); err != nil {
	return err
}
app := gas.NewApp(
	gas.WithServiceInstance[gas.ConfigProvider](cfg),
	gas.WithAllowedEnvironments(envs...),
)

Before the providers load, the extension stores the variable's value at the key when it is set, so the extensions that run after it see the environment. After they load, it stores the environment it resolved there. So once a load has stored it, the key holds a value, and a later change to `gas_env` takes effect only through the variable or the key.

Concurrency

A Config is safe for concurrent use: it may be loaded, read, written and bound from several goroutines at once. Readers take a read lock and writers a write lock, and provider I/O runs outside both.

Loads, LoadProvider included, load and merge their providers one at a time, so a provider added during a load is merged after the providers it follows. The extensions' hooks run outside that order and may call LoadProvider.

An EnvExtension is safe for concurrent use too. The built-in providers keep no state between loads.

Errors

Errors wrap one of the package's sentinel errors, to be tested with errors.Is, and the error they were caused by:

A missing file wraps fs.ErrNotExist. Bind wraps the validator's error, so errors.As finds validator.ValidationErrors.

Errors from Bind, Set, SetDefault and SetDefaults start with what failed. An error names the provider, file, extension, key or variable it is about. It never includes a value from the configuration, so a secret does not leak into logs; a syntax error gives a position instead of the text around it.

Some errors follow. The decode and parse ones are shown as the provider returns them; Load prefixes them with `failed to load from provider` and the provider's name, like the first four:

failed to load from provider static: conflicting keys: "Host" and "host"
failed to load from provider Environment Variables: conflicting variable names: "A" and "A__B"
failed to load from provider Environment Variables: environment prefix is required
failed to load from provider JSON: failed to read JSON config file app.json: config file too large
failed to decode JSON from app.json: value is not valid JSON: syntax error after byte 14
failed to parse .env file .env: 1:5: unexpected character, want newline: key: "A"
failed to execute extension pre-load hook one: boom
set defaults: conflicting keys: "B" and "b"
bind config: server.port: cannot convert string to int: invalid syntax
validate config: Key: 'AppConfig.Database.Host' Error:Field validation for 'Host' failed on the 'required' tag

Index

Constants

View Source
const (
	EnvDevelopment = gas.EnvDevelopment
	EnvTesting     = gas.EnvTesting
	EnvStaging     = gas.EnvStaging
	EnvProduction  = gas.EnvProduction
)

The environments EnvExtension allows by default, gas's standard environments.

View Source
const (
	// ExtensionName is the name EnvExtension reports.
	ExtensionName = "GasEnv"
	// DefaultConfigKey is the key EnvExtension stores the environment at,
	// and the one an Environment field binds from.
	DefaultConfigKey = "GasEnv"

	// DefaultEnvVarName is the variable EnvExtension reads the environment
	// from.
	DefaultEnvVarName = "GAS_ENV"
	// DefaultEnvironment is the environment EnvExtension falls back to.
	DefaultEnvironment = EnvDevelopment
)
View Source
const (

	// EnvProviderName is the name EnvProvider reports.
	EnvProviderName = "Environment Variables"
)

Variables

View Source
var (
	// ErrProviderLoadFailed indicates that a provider failed to load, or
	// returned keys that conflict.
	ErrProviderLoadFailed = errors.New("failed to load from provider")

	// ErrExtensionPreLoadHookFailed indicates that an extension's PreLoad
	// failed.
	ErrExtensionPreLoadHookFailed = errors.New("failed to execute extension pre-load hook")

	// ErrExtensionPostLoadHookFailed indicates that an extension's PostLoad
	// failed.
	ErrExtensionPostLoadHookFailed = errors.New("failed to execute extension post-load hook")

	// ErrNilValues indicates that SetDefaults got an untyped nil or a nil
	// pointer to a map.
	ErrNilValues = errors.New("values cannot be nil")

	// ErrInvalidKey indicates a key passed to Set or SetDefault that is
	// empty or has an empty level, such as `a..b`.
	ErrInvalidKey = errors.New("invalid key")

	// ErrKeyPathBlocked indicates that Set cannot reach a key because a
	// level on its path holds a value that is not a map.
	ErrKeyPathBlocked = errors.New("a level of the key holds a value that is not a map")

	// ErrKeyConflict indicates two keys of one map that become the same key
	// once they are trimmed and lowercased, in a provider's values or in a
	// value passed to Set, SetDefault or SetDefaults.
	ErrKeyConflict = maputil.ErrKeyConflict
)
View Source
var (
	// ErrDotEnvFilePathNotSet indicates that the `.env` file path is empty.
	ErrDotEnvFilePathNotSet = errors.New(".env file path is not set")
	// ErrDotEnvFileReadFailed indicates that the `.env` file could not be
	// read.
	ErrDotEnvFileReadFailed = errors.New("failed to read .env file")
	// ErrDotEnvParseFailed indicates that the `.env` file does not follow
	// the format, or holds names that conflict.
	ErrDotEnvParseFailed = errors.New("failed to parse .env file")
	// ErrSetEnv indicates that a variable could not be copied into the
	// process environment.
	ErrSetEnv = errors.New("failed to set os env")
)
View Source
var (
	// ErrJSONFilePathNotSet indicates that the JSON file path is not set.
	ErrJSONFilePathNotSet = errors.New("JSON file path is not set")
	// ErrJSONFileReadFailed indicates that the JSON file could not be read.
	ErrJSONFileReadFailed = errors.New("failed to read JSON config file")
	// ErrJSONDecodeFailed indicates that the file does not hold a JSON
	// object.
	ErrJSONDecodeFailed = errors.New("failed to decode JSON")
)
View Source
var ErrEnvPrefixRequired = errors.New("environment prefix is required")

ErrEnvPrefixRequired is returned by EnvProvider.Load when the provider has no prefix and was not given WithoutEnvPrefix: give it WithEnvPrefix, or WithoutEnvPrefix to load every variable.

View Source
var ErrEnvironmentNotAllowed = errors.New("environment not allowed")

ErrEnvironmentNotAllowed indicates that the environment variable, or the keys a provider sets, holds a value that EnvExtension does not allow.

Functions

This section is empty.

Types

type Config

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

Config holds the configuration that its providers load, as described in the package documentation. It is safe for concurrent use.

func New

func New(opts ...Option) *Config

New returns a Config configured by opts, holding no values until it is loaded. Without a provider, it has an EnvProvider with the default separator and no prefix, whose Load fails with ErrEnvPrefixRequired, so an app gives New the providers it loads from.

It has an EnvExtension with the default options, which runs before the extensions WithExtension adds, so the app runs in the environment GAS_ENV names. An EnvExtension given to WithExtension takes its place, and WithoutEnvExtension leaves it out.

func (*Config) Bind

func (c *Config) Bind(dest any) error

Bind fills the struct dest points to from the configuration, then validates it.

func (*Config) Find

func (c *Config) Find(key string) (value any, exist bool)

Find returns a copy of the value at key, and whether the key holds one. A key that is empty or has an empty level holds none.

func (*Config) Format added in v0.6.0

func (c *Config) Format(f fmt.State, _ rune)

Format writes String, whatever the verb, so fmt never prints a value from the configuration.

func (*Config) Get

func (c *Config) Get(key string) any

Get returns a copy of the value at key, or nil when the key holds none. A key that is empty or has an empty level holds none.

func (*Config) Load

func (c *Config) Load() error

Load is LoadWithContext with context.Background().

func (*Config) LoadProvider added in v0.4.3

func (c *Config) LoadProvider(p Provider) error

LoadProvider is LoadProviderContext with context.Background().

func (*Config) LoadProviderContext added in v0.4.3

func (c *Config) LoadProviderContext(ctx context.Context, p Provider) error

LoadProviderContext loads p, merges its values over the configuration, and adds it to the providers that later loads load. A failed load adds nothing. Extensions do not run.

func (*Config) LoadWithContext

func (c *Config) LoadWithContext(ctx context.Context) error

LoadWithContext runs each extension's PreLoad, loads every provider under ctx, merges their values over the configuration in order, and runs each extension's PostLoad. The first error stops it.

func (*Config) LogValue added in v0.6.0

func (c *Config) LogValue() slog.Value

LogValue returns a group of the counts String prints, never a value.

func (*Config) Set

func (c *Config) Set(key string, value any) error

Set stores a normalized copy of value at key, replacing what the key holds. A key that is empty or has an empty level returns an error wrapping ErrInvalidKey, a level on the path that holds a value that is not a map an error wrapping ErrKeyPathBlocked, and a map in value with two keys that become the same an error wrapping ErrKeyConflict. On an error the configuration is unchanged.

func (*Config) SetDefault

func (c *Config) SetDefault(key string, value any) error

SetDefault stores a normalized copy of value at key unless the key holds a value, or a level on its path holds a value that is not a map. A key that is empty or has an empty level returns an error wrapping ErrInvalidKey, and a map in value with two keys that become the same an error wrapping ErrKeyConflict.

func (*Config) SetDefaults

func (c *Config) SetDefaults(values any) error

SetDefaults adds the keys of a map[string]any, or the fields of a struct, that the configuration does not hold.

func (*Config) String added in v0.6.0

func (c *Config) String() string

String returns the Config's counts of providers, extensions and top-level keys, never a value, such as `config.Config{providers: 1, extensions: 1, keys: 3}`.

func (*Config) Values

func (c *Config) Values() map[string]any

Values returns a copy of the whole configuration. Without a prefix, an EnvProvider puts every environment variable it keeps into it, secrets of other tools included, so never log or print what Values returns.

type ConfigProvider added in v0.6.0

type ConfigProvider interface {
	SetDefault(key string, value any) error
	SetDefaults(values any) error
	Set(key string, value any) error
	Bind(dest any) error
	Get(key string) any
	Find(key string) (value any, exist bool)
	Values() map[string]any
}

ConfigProvider is the part of *Config that services read configuration through. Core defines gas.ConfigProvider with the same methods, which *Config satisfies.

type ContextProvider added in v0.6.0

type ContextProvider interface {
	Provider

	LoadContext(ctx context.Context) (map[string]any, error)
}

ContextProvider is a Provider that takes the context of the load. The config module calls LoadContext instead of Load on a provider that implements it.

type DotEnvOption added in v0.6.0

type DotEnvOption func(*DotEnvProvider)

DotEnvOption configures a DotEnvProvider.

func WithDotEnvFileAppendToOSEnv added in v0.6.0

func WithDotEnvFileAppendToOSEnv(appendToOSEnv bool) DotEnvOption

WithDotEnvFileAppendToOSEnv sets whether each load also copies the file's variables into the process environment, apart from the unsafe ones. Child processes then inherit them, secrets included, and a variable in the file replaces one the process had.

Default: false.

func WithDotEnvFileFS added in v0.6.0

func WithDotEnvFileFS(fileFS fs.FS) DotEnvOption

WithDotEnvFileFS makes the provider read the file from fileFS, such as an embed.FS, instead of the working directory. A nil fileFS reads from the working directory.

func WithDotEnvFileNotFoundPanic added in v0.6.0

func WithDotEnvFileNotFoundPanic(panicIfNotFound bool) DotEnvOption

WithDotEnvFileNotFoundPanic sets whether a missing `.env` file is an error, wrapping ErrDotEnvFileReadFailed. With false, a missing file loads no values. Despite the name, nothing panics.

Default: true.

func WithDotEnvFilePath added in v0.6.0

func WithDotEnvFilePath(filePath string) DotEnvOption

WithDotEnvFilePath sets the path of the `.env` file.

Default: `.env`.

func WithDotEnvSeparator added in v0.6.0

func WithDotEnvSeparator(sep string) DotEnvOption

WithDotEnvSeparator sets the text that separates the levels of a name, as WithEnvSeparator does for EnvProvider.

Default: `__`.

type DotEnvProvider added in v0.6.0

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

DotEnvProvider loads configuration from a `.env` file, as described in the package documentation.

func NewDotEnvProvider added in v0.6.0

func NewDotEnvProvider(opts ...DotEnvOption) *DotEnvProvider

NewDotEnvProvider returns a DotEnvProvider configured by opts.

func (*DotEnvProvider) Load added in v0.6.0

func (p *DotEnvProvider) Load() (map[string]any, error)

Load reads the file.

func (*DotEnvProvider) Name added in v0.6.0

func (p *DotEnvProvider) Name() string

Name returns "DotEnv".

type EnvExtension added in v0.6.0

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

EnvExtension resolves the application environment during each load, as described in the package documentation: from the variable `GAS_ENV`, else from the key `GasEnv`, else from the key `gas_env`, else the fallback, development. So the variable wins over a provider, and a `.env` file may set the environment as `GAS_ENV` or `GASENV`.

func NewEnvExtension added in v0.6.1

func NewEnvExtension(opts ...EnvOption) *EnvExtension

NewEnvExtension returns an EnvExtension configured by opts.

func (*EnvExtension) Current added in v0.6.0

func (em *EnvExtension) Current() Environment

Current returns the environment the last load resolved, or the empty Environment before the first load.

func (*EnvExtension) Is added in v0.6.0

func (em *EnvExtension) Is(env Environment) bool

Is reports whether the current environment is env.

func (*EnvExtension) IsDevelopment added in v0.6.0

func (em *EnvExtension) IsDevelopment() bool

IsDevelopment reports whether the current environment is EnvDevelopment.

func (*EnvExtension) IsDevelopmentLike added in v0.6.0

func (em *EnvExtension) IsDevelopmentLike() bool

IsDevelopmentLike reports whether the current environment is EnvDevelopment or EnvTesting.

func (*EnvExtension) IsProduction added in v0.6.0

func (em *EnvExtension) IsProduction() bool

IsProduction reports whether the current environment is EnvProduction.

func (*EnvExtension) IsProductionLike added in v0.6.0

func (em *EnvExtension) IsProductionLike() bool

IsProductionLike reports whether the current environment is EnvProduction or EnvStaging.

func (*EnvExtension) IsStaging added in v0.6.0

func (em *EnvExtension) IsStaging() bool

IsStaging reports whether the current environment is EnvStaging.

func (*EnvExtension) IsTesting added in v0.6.0

func (em *EnvExtension) IsTesting() bool

IsTesting reports whether the current environment is EnvTesting.

func (*EnvExtension) Name added in v0.6.0

func (em *EnvExtension) Name() string

Name returns ExtensionName.

func (*EnvExtension) PostLoad added in v0.6.0

func (em *EnvExtension) PostLoad(_ context.Context, cfg *Config) error

PostLoad resolves the environment, stores it at the key and makes it the current one. A source that holds anything but an allowed environment, as a string, is an error wrapping ErrEnvironmentNotAllowed, and the current environment stays as it was.

func (*EnvExtension) PreLoad added in v0.6.0

func (em *EnvExtension) PreLoad(_ context.Context, cfg *Config) error

PreLoad checks the variable, and stores its environment at the key when it is set and not empty, so the extensions that run after it see the environment the load resolves. A variable that holds an environment that is not allowed is an error wrapping ErrEnvironmentNotAllowed.

type EnvOption added in v0.6.0

type EnvOption func(*EnvExtension)

EnvOption configures an EnvExtension.

func WithAllowedEnvs added in v0.6.0

func WithAllowedEnvs(envs ...Environment) EnvOption

WithAllowedEnvs sets the environments the extension accepts. An App accepts only the environments gas.WithAllowedEnvironments sets, so give it the same ones, or App.Start fails on any environment outside gas's four standard ones.

Default: EnvDevelopment, EnvTesting, EnvStaging and EnvProduction.

func WithConfigKey added in v0.6.0

func WithConfigKey(key string) EnvOption

WithConfigKey sets the key the extension reads and stores the environment at. With another key than DefaultConfigKey, the environment is stored at DefaultConfigKey too.

Default: DefaultConfigKey.

func WithDefault added in v0.6.0

func WithDefault(env Environment) EnvOption

WithDefault sets the environment the extension falls back to when neither the variable nor a key sets one. The fallback is allowed even when it is not one of the allowed environments. An App does not allow it that way: a fallback outside gas's four standard environments must also be given to gas.WithAllowedEnvironments, or App.Start fails.

Default: DefaultEnvironment.

func WithEnvVarName added in v0.6.0

func WithEnvVarName(name string) EnvOption

WithEnvVarName sets the variable the extension reads the environment from. It also sets the key the extension reads after its own: the key EnvProvider and DotEnvProvider make of the name, such as `app_env` for `APP_ENV`.

Default: DefaultEnvVarName.

type EnvProvider added in v0.6.0

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

EnvProvider loads configuration from the process environment, as described in the package documentation. It needs WithEnvPrefix, or WithoutEnvPrefix to load every variable it keeps, such as another tool's API key or a DATABASE_URL; without either, Load fails with ErrEnvPrefixRequired.

func NewEnvProvider added in v0.6.0

func NewEnvProvider(opts ...EnvProviderOption) *EnvProvider

NewEnvProvider returns an EnvProvider configured by opts.

func (*EnvProvider) Load added in v0.6.0

func (p *EnvProvider) Load() (map[string]any, error)

Load reads the process environment. A provider with no prefix that was not given WithoutEnvPrefix returns ErrEnvPrefixRequired and reads nothing.

func (*EnvProvider) Name added in v0.6.0

func (p *EnvProvider) Name() string

Name returns EnvProviderName.

type EnvProviderOption added in v0.6.0

type EnvProviderOption func(*EnvProvider)

EnvProviderOption configures an EnvProvider.

func WithEnvPrefix added in v0.6.0

func WithEnvPrefix(prefix string) EnvProviderOption

WithEnvPrefix keeps only the variables whose names start with prefix, without regard to case, and removes it from their names. The separator is not added, so `APP_` keeps `APP_HOST` as `host`, where `APP` would make it `_host`. An empty prefix is no prefix.

func WithEnvSeparator added in v0.6.0

func WithEnvSeparator(sep string) EnvProviderOption

WithEnvSeparator sets the text that separates the levels of a name, so with `__`, `DATABASE__HOST` is the key `host` under `database`. An empty separator keeps every name one level.

Default: `__`.

func WithoutEnvPrefix added in v0.6.0

func WithoutEnvPrefix() EnvProviderOption

WithoutEnvPrefix makes the provider load every variable it keeps, with no prefix. The configuration then holds variables of other tools, such as their API keys, so never log Config.Values. The last of WithEnvPrefix and WithoutEnvPrefix wins.

type Environment added in v0.6.0

type Environment = gas.Environment

Environment is an application environment, such as development or production. It is gas.Environment, so a value from either package passes for the other, and it has gas.Environment's methods, such as IsDevelopment and IsProductionLike.

type Extension

type Extension interface {
	// Name names the extension in errors.
	Name() string
	// PreLoad runs before any provider loads.
	PreLoad(ctx context.Context, cfg *Config) error
	// PostLoad runs after the providers' values are merged.
	PostLoad(ctx context.Context, cfg *Config) error
}

Extension runs code before and after the providers load, as described in the package documentation.

type JSONOption added in v0.6.0

type JSONOption func(*JSONProvider)

JSONOption configures a JSONProvider.

func WithJSONFileFS added in v0.6.0

func WithJSONFileFS(fileFS fs.FS) JSONOption

WithJSONFileFS makes the provider read the file from fileFS, such as an embed.FS, instead of the working directory. A nil fileFS reads from the working directory.

func WithJSONFilePath added in v0.6.0

func WithJSONFilePath(filePath string) JSONOption

WithJSONFilePath sets the path of the JSON file. It has no default.

type JSONProvider added in v0.6.0

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

JSONProvider loads configuration from a JSON file, as described in the package documentation.

func NewJSONProvider added in v0.6.0

func NewJSONProvider(opts ...JSONOption) *JSONProvider

NewJSONProvider returns a JSONProvider configured by opts.

func (*JSONProvider) Load added in v0.6.0

func (p *JSONProvider) Load() (map[string]any, error)

Load reads the file.

func (*JSONProvider) Name added in v0.6.0

func (p *JSONProvider) Name() string

Name returns "JSON".

type Option

type Option func(*Config)

Option configures a Config.

func WithExtension

func WithExtension(ext Extension) Option

WithExtension adds an extension. Extensions run in the order they are added.

func WithProvider

func WithProvider(p Provider) Option

WithProvider adds a provider. Providers load in the order they are added, a later one winning.

func WithValidator

func WithValidator(v Validator) Option

WithValidator sets the validator Bind checks structs with, such as one with custom validation tags registered. A nil validator, a nil pointer such as a nil *validator.Validate included, keeps the default, validator.New().

func WithoutEnvExtension added in v0.10.0

func WithoutEnvExtension() Option

WithoutEnvExtension leaves out the EnvExtension that New adds by default, so the configuration does not read GAS_ENV, check it, or store the environment at DefaultConfigKey. An EnvExtension given to WithExtension still runs.

type Provider added in v0.6.0

type Provider interface {
	// Name names the provider in errors.
	Name() string
	// Load reads the provider's values. Each load calls it again.
	Load() (map[string]any, error)
}

Provider is a source of configuration values, such as the environment, a file or a secret store, as described in the package documentation.

type Validator added in v0.6.0

type Validator interface {
	StructCtx(ctx context.Context, s any) error
}

Validator checks a struct after Bind fills it. *validator.Validate from github.com/go-playground/validator/v10 implements it, and New uses one unless WithValidator passes another.

Directories

Path Synopsis
Package configtest holds MockConfig, a config.ConfigProvider for tests of code that reads configuration, and StaticProvider, a config.Provider that loads fixed values.
Package configtest holds MockConfig, a config.ConfigProvider for tests of code that reads configuration, and StaticProvider, a config.Provider that loads fixed values.
internal
dotenv
Package dotenv parses `.env` files into a map of keys to string values.
Package dotenv parses `.env` files into a map of keys to string values.
env
Package env turns environment variables into the nested map of keys to values that the config module merges.
Package env turns environment variables into the nested map of keys to values that the config module merges.
jsonobj
Package jsonobj decodes a JSON object for the config module's JSON provider and its Secrets Manager provider, with errors that never quote the input.
Package jsonobj decodes a JSON object for the config module's JSON provider and its Secrets Manager provider, with errors that never quote the input.
maputil
Package maputil holds the map operations behind the config module.
Package maputil holds the map operations behind the config module.
providers
Package providers holds FSProvider, which reads the file behind the config module's JSON and `.env` providers.
Package providers holds FSProvider, which reads the file behind the config module's JSON and `.env` providers.
reflection
Package reflection holds Clone, the deep copy behind the config module.
Package reflection holds Clone, the deep copy behind the config module.
sysfs
Package sysfs holds SysFS, the file system the config module's JSON and `.env` providers read through by default.
Package sysfs holds SysFS, the file system the config module's JSON and `.env` providers read through by default.
Package secretsmanager is a config provider that loads values from AWS Secrets Manager.
Package secretsmanager is a config provider that loads values from AWS Secrets Manager.

Jump to

Keyboard shortcuts

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