gas/config
config
import "github.com/gasmod/gas/config"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.
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 AppConfigapp.Database.Port = 5432 // kept unless the configuration sets itif 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
Section titled “Providers”A Provider returns a map of values each time it loads. The package has three:
- EnvProvider reads the process environment.
- DotEnvProvider reads a
.envfile. - JSONProvider reads a JSON file.
Package secretsmanager reads AWS Secrets Manager.
Environment variables
Section titled “Environment variables”EnvProvider reads the process environment, and turns each variable’s name into a key:
__separates the levels of a name, soDATABASE__HOSTis the keyhostunderdatabase. WithEnvSeparator changes it, and an empty separator keeps every name one level.- Names are lowercased.
- A name with an empty level, such as
A____Bwith__, 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
Section titled “The .env file”DotEnvProvider reads a .env file, and turns its names into keys as
EnvProvider does:
- The file is
.envunless WithDotEnvFilePath says otherwise. - WithDotEnvSeparator sets the separator. There is no prefix.
- A missing file is an error, unless WithDotEnvFileNotFoundPanic is passed false: then it loads no values.
The format is small and strict, and anything outside it is an error:
# a commentDB__HOST=localhostDB__PORT = 5432 # spaces around "=" are allowedDB__NAME="app db" # quotes keep spaces and "#", and may span linesDB__URL=postgres://${DB__HOST}:${DB__PORT}/appDB__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 noexport. - 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
Section titled “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
Section titled “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
Section titled “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
Section titled “Loading”Config.Load, or Config.LoadWithContext, runs these steps, in order:
- It runs each extension’s PreLoad.
- It loads every provider, in the order they were added.
- It merges their values over the configuration, in that order (see Merging).
- 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
Section titled “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.
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
Section titled “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
Section titled “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
Section titled “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
Section titled “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 string8080.0is 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:
30sworks,30is an error, and0is zero. - nil sets the field to its zero value, and a pointer field is allocated when it is nil.
Validation
Section titled “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
Section titled “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 noGasEnvunless 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
Section titled “Resolving the environment”The environment is the first of these:
- The value of the variable
GAS_ENV, unless it is unset or empty. - Else the value at the key,
gasenv, such asGASENVin a.envfile sets. - Else the value at
gas_env, the key that EnvProvider and DotEnvProvider make of the variable’s name, such asGAS_ENVin a.envfile sets. The empty string there counts as unset, as it does for the variable. - 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_envforAPP_ENV. - WithAllowedEnvs changes the allowed values.
- WithDefault changes the fallback.
- WithConfigKey changes the key. With another key, the environment
is stored at
GasEnvtoo.
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, productionGive 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
Section titled “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
Section titled “Errors”Errors wrap one of the package’s sentinel errors, to be tested with errors.Is, and the error they were caused by:
- ErrProviderLoadFailed: a provider failed to load, or two of its keys conflict. The provider’s own error is wrapped too, such as one of the provider sentinels below.
- ErrExtensionPreLoadHookFailed, ErrExtensionPostLoadHookFailed: an extension’s hook failed.
- ErrEnvironmentNotAllowed: the environment variable, or the key EnvExtension reads, holds an environment that is not allowed. It is wrapped with one of the two above.
- ErrNilValues: SetDefaults got an untyped nil, or a nil pointer to a map. A nil map adds nothing, without an error.
- ErrInvalidKey: Set or SetDefault got a key that is empty or has an empty level.
- ErrKeyPathBlocked: Set got a key under a level that holds a value that is not a map.
- ErrKeyConflict: two keys of one map become the same key once trimmed and lowercased, in a provider’s values, wrapped with ErrProviderLoadFailed, or in a value given to Set, SetDefault or SetDefaults. Two environment variable names that conflict wrap ErrProviderLoadFailed only.
- ErrEnvPrefixRequired: an EnvProvider has no prefix and was not given WithoutEnvPrefix. It is wrapped with ErrProviderLoadFailed.
- ErrJSONFilePathNotSet, ErrJSONFileReadFailed, ErrJSONDecodeFailed: the JSON provider has no path, cannot read the file, or the file does not hold a JSON object.
- ErrDotEnvFilePathNotSet, ErrDotEnvFileReadFailed,
ErrDotEnvParseFailed, ErrSetEnv: the
.envprovider has an empty path, cannot read the file, finds a file outside the format or names that conflict, or cannot copy a variable into the process environment.
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 requiredfailed to load from provider JSON: failed to read JSON config file app.json: config file too largefailed to decode JSON from app.json: value is not valid JSON: syntax error after byte 14failed to parse .env file .env: 1:5: unexpected character, want newline: key: "A"failed to execute extension pre-load hook one: boomset defaults: conflicting keys: "B" and "b"bind config: server.port: cannot convert string to int: invalid syntaxvalidate config: Key: 'AppConfig.Database.Host' Error:Field validation for 'Host' failed on the 'required' tagAPI reference
Section titled “API reference”Constants
Section titled “Constants”const ( EnvDevelopment = gas.EnvDevelopment EnvTesting = gas.EnvTesting EnvStaging = gas.EnvStaging EnvProduction = gas.EnvProduction)The environments EnvExtension allows by default, gas’s standard environments.
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)const (
// EnvProviderName is the name EnvProvider reports. EnvProviderName = "Environment Variables")Variables
Section titled “Variables”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)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"))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"))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.
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.
type Config
Section titled “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
Section titled “func New”func New(opts ...Option) *ConfigNew 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
Section titled “func (*Config) Bind”func (c *Config) Bind(dest any) errorBind fills the struct dest points to from the configuration, then validates it.
func (*Config) Find
Section titled “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
Section titled “func (*Config) Format”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
Section titled “func (*Config) Get”func (c *Config) Get(key string) anyGet 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
Section titled “func (*Config) Load”func (c *Config) Load() errorLoad is LoadWithContext with context.Background().
func (*Config) LoadProvider
Section titled “func (*Config) LoadProvider”func (c *Config) LoadProvider(p Provider) errorLoadProvider is LoadProviderContext with context.Background().
func (*Config) LoadProviderContext
Section titled “func (*Config) LoadProviderContext”func (c *Config) LoadProviderContext(ctx context.Context, p Provider) errorLoadProviderContext 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
Section titled “func (*Config) LoadWithContext”func (c *Config) LoadWithContext(ctx context.Context) errorLoadWithContext 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
Section titled “func (*Config) LogValue”func (c *Config) LogValue() slog.ValueLogValue returns a group of the counts String prints, never a value.
func (*Config) Set
Section titled “func (*Config) Set”func (c *Config) Set(key string, value any) errorSet 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
Section titled “func (*Config) SetDefault”func (c *Config) SetDefault(key string, value any) errorSetDefault 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
Section titled “func (*Config) SetDefaults”func (c *Config) SetDefaults(values any) errorSetDefaults adds the keys of a map[string]any, or the fields of a struct, that the configuration does not hold.
func (*Config) String
Section titled “func (*Config) String”func (c *Config) String() stringString 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
Section titled “func (*Config) Values”func (c *Config) Values() map[string]anyValues 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
Section titled “type ConfigProvider”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
Section titled “type ContextProvider”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
Section titled “type DotEnvOption”type DotEnvOption func(*DotEnvProvider)DotEnvOption configures a DotEnvProvider.
func WithDotEnvFileAppendToOSEnv
Section titled “func WithDotEnvFileAppendToOSEnv”func WithDotEnvFileAppendToOSEnv(appendToOSEnv bool) DotEnvOptionWithDotEnvFileAppendToOSEnv 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
Section titled “func WithDotEnvFileFS”func WithDotEnvFileFS(fileFS fs.FS) DotEnvOptionWithDotEnvFileFS 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
Section titled “func WithDotEnvFileNotFoundPanic”func WithDotEnvFileNotFoundPanic(panicIfNotFound bool) DotEnvOptionWithDotEnvFileNotFoundPanic 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
Section titled “func WithDotEnvFilePath”func WithDotEnvFilePath(filePath string) DotEnvOptionWithDotEnvFilePath sets the path of the .env file.
Default: .env.
func WithDotEnvSeparator
Section titled “func WithDotEnvSeparator”func WithDotEnvSeparator(sep string) DotEnvOptionWithDotEnvSeparator sets the text that separates the levels of a name, as WithEnvSeparator does for EnvProvider.
Default: __.
type DotEnvProvider
Section titled “type DotEnvProvider”type DotEnvProvider struct { // contains filtered or unexported fields}DotEnvProvider loads configuration from a .env file, as described in
the package documentation.
func NewDotEnvProvider
Section titled “func NewDotEnvProvider”func NewDotEnvProvider(opts ...DotEnvOption) *DotEnvProviderNewDotEnvProvider returns a DotEnvProvider configured by opts.
func (*DotEnvProvider) Load
Section titled “func (*DotEnvProvider) Load”func (p *DotEnvProvider) Load() (map[string]any, error)Load reads the file.
func (*DotEnvProvider) Name
Section titled “func (*DotEnvProvider) Name”func (p *DotEnvProvider) Name() stringName returns “DotEnv”.
type EnvExtension
Section titled “type EnvExtension”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
Section titled “func NewEnvExtension”func NewEnvExtension(opts ...EnvOption) *EnvExtensionNewEnvExtension returns an EnvExtension configured by opts.
func (*EnvExtension) Current
Section titled “func (*EnvExtension) Current”func (em *EnvExtension) Current() EnvironmentCurrent returns the environment the last load resolved, or the empty Environment before the first load.
func (*EnvExtension) Is
Section titled “func (*EnvExtension) Is”func (em *EnvExtension) Is(env Environment) boolIs reports whether the current environment is env.
func (*EnvExtension) IsDevelopment
Section titled “func (*EnvExtension) IsDevelopment”func (em *EnvExtension) IsDevelopment() boolIsDevelopment reports whether the current environment is EnvDevelopment.
func (*EnvExtension) IsDevelopmentLike
Section titled “func (*EnvExtension) IsDevelopmentLike”func (em *EnvExtension) IsDevelopmentLike() boolIsDevelopmentLike reports whether the current environment is EnvDevelopment or EnvTesting.
func (*EnvExtension) IsProduction
Section titled “func (*EnvExtension) IsProduction”func (em *EnvExtension) IsProduction() boolIsProduction reports whether the current environment is EnvProduction.
func (*EnvExtension) IsProductionLike
Section titled “func (*EnvExtension) IsProductionLike”func (em *EnvExtension) IsProductionLike() boolIsProductionLike reports whether the current environment is EnvProduction or EnvStaging.
func (*EnvExtension) IsStaging
Section titled “func (*EnvExtension) IsStaging”func (em *EnvExtension) IsStaging() boolIsStaging reports whether the current environment is EnvStaging.
func (*EnvExtension) IsTesting
Section titled “func (*EnvExtension) IsTesting”func (em *EnvExtension) IsTesting() boolIsTesting reports whether the current environment is EnvTesting.
func (*EnvExtension) Name
Section titled “func (*EnvExtension) Name”func (em *EnvExtension) Name() stringName returns ExtensionName.
func (*EnvExtension) PostLoad
Section titled “func (*EnvExtension) PostLoad”func (em *EnvExtension) PostLoad(_ context.Context, cfg *Config) errorPostLoad 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
Section titled “func (*EnvExtension) PreLoad”func (em *EnvExtension) PreLoad(_ context.Context, cfg *Config) errorPreLoad 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
Section titled “type EnvOption”type EnvOption func(*EnvExtension)EnvOption configures an EnvExtension.
func WithAllowedEnvs
Section titled “func WithAllowedEnvs”func WithAllowedEnvs(envs ...Environment) EnvOptionWithAllowedEnvs 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
Section titled “func WithConfigKey”func WithConfigKey(key string) EnvOptionWithConfigKey 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
Section titled “func WithDefault”func WithDefault(env Environment) EnvOptionWithDefault 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
Section titled “func WithEnvVarName”func WithEnvVarName(name string) EnvOptionWithEnvVarName 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
Section titled “type EnvProvider”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
Section titled “func NewEnvProvider”func NewEnvProvider(opts ...EnvProviderOption) *EnvProviderNewEnvProvider returns an EnvProvider configured by opts.
func (*EnvProvider) Load
Section titled “func (*EnvProvider) Load”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
Section titled “func (*EnvProvider) Name”func (p *EnvProvider) Name() stringName returns EnvProviderName.
type EnvProviderOption
Section titled “type EnvProviderOption”type EnvProviderOption func(*EnvProvider)EnvProviderOption configures an EnvProvider.
func WithEnvPrefix
Section titled “func WithEnvPrefix”func WithEnvPrefix(prefix string) EnvProviderOptionWithEnvPrefix 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
Section titled “func WithEnvSeparator”func WithEnvSeparator(sep string) EnvProviderOptionWithEnvSeparator 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
Section titled “func WithoutEnvPrefix”func WithoutEnvPrefix() EnvProviderOptionWithoutEnvPrefix 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
Section titled “type Environment”type Environment = gas.EnvironmentEnvironment 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
Section titled “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
Section titled “type JSONOption”type JSONOption func(*JSONProvider)JSONOption configures a JSONProvider.
func WithJSONFileFS
Section titled “func WithJSONFileFS”func WithJSONFileFS(fileFS fs.FS) JSONOptionWithJSONFileFS 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
Section titled “func WithJSONFilePath”func WithJSONFilePath(filePath string) JSONOptionWithJSONFilePath sets the path of the JSON file. It has no default.
type JSONProvider
Section titled “type JSONProvider”type JSONProvider struct { // contains filtered or unexported fields}JSONProvider loads configuration from a JSON file, as described in the package documentation.
func NewJSONProvider
Section titled “func NewJSONProvider”func NewJSONProvider(opts ...JSONOption) *JSONProviderNewJSONProvider returns a JSONProvider configured by opts.
func (*JSONProvider) Load
Section titled “func (*JSONProvider) Load”func (p *JSONProvider) Load() (map[string]any, error)Load reads the file.
func (*JSONProvider) Name
Section titled “func (*JSONProvider) Name”func (p *JSONProvider) Name() stringName returns “JSON”.
type Option
Section titled “type Option”type Option func(*Config)Option configures a Config.
func WithExtension
Section titled “func WithExtension”func WithExtension(ext Extension) OptionWithExtension adds an extension. Extensions run in the order they are added.
func WithProvider
Section titled “func WithProvider”func WithProvider(p Provider) OptionWithProvider adds a provider. Providers load in the order they are added, a later one winning.
func WithValidator
Section titled “func WithValidator”func WithValidator(v Validator) OptionWithValidator 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
Section titled “func WithoutEnvExtension”func WithoutEnvExtension() OptionWithoutEnvExtension 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
Section titled “type Provider”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
Section titled “type Validator”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.