## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# 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.

The Markdown of https://gasmod.dev/reference/config/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
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.

## Usage

Build a [Config](#Config) with its providers, load it, and bind a struct:

```go
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](#EnvProvider) with the default separator and no prefix, which fails
to load with [ErrEnvPrefixRequired](#ErrEnvPrefixRequired).

\*Config implements [ConfigProvider](#ConfigProvider), the interface services read
configuration through.

## Providers

A [Provider](#Provider) returns a map of values each time it loads. The package has
three:

- [EnvProvider](#EnvProvider) reads the process environment.
- [DotEnvProvider](#DotEnvProvider) reads a `.env` file.
- [JSONProvider](#JSONProvider) reads a JSON file.

Package secretsmanager reads AWS Secrets Manager.

## Environment variables

[EnvProvider](#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](#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](#ErrEnvPrefixRequired) and reads nothing. [WithEnvPrefix](#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](#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](#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](#DotEnvProvider) reads a `.env` file, and turns its names into keys as
EnvProvider does:

- The file is `.env` unless [WithDotEnvFilePath](#WithDotEnvFilePath) says otherwise.
- [WithDotEnvSeparator](#WithDotEnvSeparator) sets the separator. There is no prefix.
- A missing file is an error, unless [WithDotEnvFileNotFoundPanic](#WithDotEnvFileNotFoundPanic) is
passed false: then it loads no values.

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

```go
# 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](#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](#JSONProvider) reads a JSON file, whose path [WithJSONFilePath](#WithJSONFilePath) sets; it
has no default. The file must hold an object.

Its values have the types [encoding/json](https://pkg.go.dev/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](#WithJSONFileFS) and [WithDotEnvFileFS](#WithDotEnvFileFS) read from any [fs.FS](https://pkg.go.dev/io/fs#FS) instead,
such as an [embed.FS](https://pkg.go.dev/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](#Provider). One that should take the load's
context also implements [ContextProvider](#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](#Config.Load), or [Config.LoadWithContext](#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](#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.Get), [Config.Find](#Config.Find), [Config.Set](#Config.Set) and [Config.SetDefault](#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](#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](#Config.Find)
also reports whether the key holds a value, which tells a key holding nil
from a missing one. [Config.Values](#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](#ErrKeyPathBlocked) and
changes nothing.

[Config.SetDefault](#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](#ErrKeyConflict), and nothing is stored.

## Defaults

[Config.SetDefaults](#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](#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](#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](https://pkg.go.dev/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](https://pkg.go.dev/fmt#Sprint), except that a float is written without an exponent, so
1234567.0 is `1234567`.
- A [time.Duration](https://pkg.go.dev/time#Duration) field takes a string that [time.ParseDuration](https://pkg.go.dev/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](#Validator). By
default that is \*validator.Validate from
github.com/go-playground/validator/v10, which reads `validate` struct
tags. [WithValidator](#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](#EnvExtension) resolves the environment the app runs in, such as
development or production, during each load, and stores it at the key
`GasEnv`.

[New](#New) adds an EnvExtension with the default options, which runs before
the extensions [WithExtension](#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](#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](#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](#WithConfigKey) set to `env`, it binds without
one:

```go
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:

```go
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](#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](#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](#WithEnvVarName) changes the variable, and with it the key made of
its name, such as `app_env` for `APP_ENV`.
- [WithAllowedEnvs](#WithAllowedEnvs) changes the allowed values.
- [WithDefault](#WithDefault) changes the fallback.
- [WithConfigKey](#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:

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

Give both the same environments:

```go
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](https://pkg.go.dev/errors#Is), and the error they were caused by:

- [ErrProviderLoadFailed](#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](#ErrExtensionPreLoadHookFailed), [ErrExtensionPostLoadHookFailed](#ErrExtensionPostLoadHookFailed): an
extension's hook failed.
- [ErrEnvironmentNotAllowed](#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](#ErrNilValues): SetDefaults got an untyped nil, or a nil pointer to a
map. A nil map adds nothing, without an error.
- [ErrInvalidKey](#ErrInvalidKey): Set or SetDefault got a key that is empty or has an
empty level.
- [ErrKeyPathBlocked](#ErrKeyPathBlocked): Set got a key under a level that holds a value
that is not a map.
- [ErrKeyConflict](#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](#ErrEnvPrefixRequired): an EnvProvider has no prefix and was not
given WithoutEnvPrefix. It is wrapped with ErrProviderLoadFailed.
- [ErrJSONFilePathNotSet](#ErrJSONFilePathNotSet), [ErrJSONFileReadFailed](#ErrJSONFileReadFailed),
[ErrJSONDecodeFailed](#ErrJSONDecodeFailed): the JSON provider has no path, cannot read the
file, or the file does not hold a JSON object.
- [ErrDotEnvFilePathNotSet](#ErrDotEnvFilePathNotSet), [ErrDotEnvFileReadFailed](#ErrDotEnvFileReadFailed),
[ErrDotEnvParseFailed](#ErrDotEnvParseFailed), [ErrSetEnv](#ErrSetEnv): the `.env` provider 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](https://pkg.go.dev/io/fs#ErrNotExist). Bind wraps the validator's error,
so [errors.As](https://pkg.go.dev/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:

```go
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
```


## API reference

### Constants

<a id="EnvDevelopment"></a><a id="EnvTesting"></a><a id="EnvStaging"></a><a id="EnvProduction"></a>

```go
const (
	EnvDevelopment = gas.EnvDevelopment
	EnvTesting     = gas.EnvTesting
	EnvStaging     = gas.EnvStaging
	EnvProduction  = gas.EnvProduction
)
```

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

<a id="ExtensionName"></a><a id="DefaultConfigKey"></a><a id="DefaultEnvVarName"></a><a id="DefaultEnvironment"></a>

```go
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
)
```

<a id="EnvProviderName"></a>

```go
const (

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

### Variables

<a id="ErrProviderLoadFailed"></a><a id="ErrExtensionPreLoadHookFailed"></a><a id="ErrExtensionPostLoadHookFailed"></a><a id="ErrNilValues"></a><a id="ErrInvalidKey"></a><a id="ErrKeyPathBlocked"></a><a id="ErrKeyConflict"></a>

```go
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
)
```

<a id="ErrDotEnvFilePathNotSet"></a><a id="ErrDotEnvFileReadFailed"></a><a id="ErrDotEnvParseFailed"></a><a id="ErrSetEnv"></a>

```go
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")
)
```

<a id="ErrJSONFilePathNotSet"></a><a id="ErrJSONFileReadFailed"></a><a id="ErrJSONDecodeFailed"></a>

```go
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")
)
```

<a id="ErrEnvPrefixRequired"></a>

```go
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.

<a id="ErrEnvironmentNotAllowed"></a>

```go
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.

<a id="Config"></a>

### type Config

```go
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.

<a id="New"></a>

#### func New

```go
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.

<a id="Config.Bind"></a>

#### func (*Config) Bind

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

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

<a id="Config.Find"></a>

#### func (*Config) Find

```go
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.

<a id="Config.Format"></a>

#### func (*Config) Format

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

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

<a id="Config.Get"></a>

#### func (*Config) Get

```go
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.

<a id="Config.Load"></a>

#### func (*Config) Load

```go
func (c *Config) Load() error
```

Load is LoadWithContext with context.Background().

<a id="Config.LoadProvider"></a>

#### func (*Config) LoadProvider

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

LoadProvider is LoadProviderContext with context.Background().

<a id="Config.LoadProviderContext"></a>

#### func (*Config) LoadProviderContext

```go
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.

<a id="Config.LoadWithContext"></a>

#### func (*Config) LoadWithContext

```go
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.

<a id="Config.LogValue"></a>

#### func (*Config) LogValue

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

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

<a id="Config.Set"></a>

#### func (*Config) Set

```go
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.

<a id="Config.SetDefault"></a>

#### func (*Config) SetDefault

```go
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.

<a id="Config.SetDefaults"></a>

#### func (*Config) SetDefaults

```go
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.

<a id="Config.String"></a>

#### func (*Config) String

```go
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}`.

<a id="Config.Values"></a>

#### func (*Config) Values

```go
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.

<a id="ConfigProvider"></a><a id="ConfigProvider.SetDefault"></a><a id="ConfigProvider.SetDefaults"></a><a id="ConfigProvider.Set"></a><a id="ConfigProvider.Bind"></a><a id="ConfigProvider.Get"></a><a id="ConfigProvider.Find"></a><a id="ConfigProvider.Values"></a>

### type ConfigProvider

```go
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.

<a id="ContextProvider"></a><a id="ContextProvider.LoadContext"></a>

### type ContextProvider

```go
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.

<a id="DotEnvOption"></a>

### type DotEnvOption

```go
type DotEnvOption func(*DotEnvProvider)
```

DotEnvOption configures a DotEnvProvider.

<a id="WithDotEnvFileAppendToOSEnv"></a>

#### func WithDotEnvFileAppendToOSEnv

```go
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.

<a id="WithDotEnvFileFS"></a>

#### func WithDotEnvFileFS

```go
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.

<a id="WithDotEnvFileNotFoundPanic"></a>

#### func WithDotEnvFileNotFoundPanic

```go
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.

<a id="WithDotEnvFilePath"></a>

#### func WithDotEnvFilePath

```go
func WithDotEnvFilePath(filePath string) DotEnvOption
```

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

Default: `.env`.

<a id="WithDotEnvSeparator"></a>

#### func WithDotEnvSeparator

```go
func WithDotEnvSeparator(sep string) DotEnvOption
```

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

Default: `__`.

<a id="DotEnvProvider"></a>

### type DotEnvProvider

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

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

<a id="NewDotEnvProvider"></a>

#### func NewDotEnvProvider

```go
func NewDotEnvProvider(opts ...DotEnvOption) *DotEnvProvider
```

NewDotEnvProvider returns a DotEnvProvider configured by opts.

<a id="DotEnvProvider.Load"></a>

#### func (*DotEnvProvider) Load

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

Load reads the file.

<a id="DotEnvProvider.Name"></a>

#### func (*DotEnvProvider) Name

```go
func (p *DotEnvProvider) Name() string
```

Name returns "DotEnv".

<a id="EnvExtension"></a>

### type EnvExtension

```go
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`.

<a id="NewEnvExtension"></a>

#### func NewEnvExtension

```go
func NewEnvExtension(opts ...EnvOption) *EnvExtension
```

NewEnvExtension returns an EnvExtension configured by opts.

<a id="EnvExtension.Current"></a>

#### func (*EnvExtension) Current

```go
func (em *EnvExtension) Current() Environment
```

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

<a id="EnvExtension.Is"></a>

#### func (*EnvExtension) Is

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

Is reports whether the current environment is env.

<a id="EnvExtension.IsDevelopment"></a>

#### func (*EnvExtension) IsDevelopment

```go
func (em *EnvExtension) IsDevelopment() bool
```

IsDevelopment reports whether the current environment is EnvDevelopment.

<a id="EnvExtension.IsDevelopmentLike"></a>

#### func (*EnvExtension) IsDevelopmentLike

```go
func (em *EnvExtension) IsDevelopmentLike() bool
```

IsDevelopmentLike reports whether the current environment is
EnvDevelopment or EnvTesting.

<a id="EnvExtension.IsProduction"></a>

#### func (*EnvExtension) IsProduction

```go
func (em *EnvExtension) IsProduction() bool
```

IsProduction reports whether the current environment is EnvProduction.

<a id="EnvExtension.IsProductionLike"></a>

#### func (*EnvExtension) IsProductionLike

```go
func (em *EnvExtension) IsProductionLike() bool
```

IsProductionLike reports whether the current environment is EnvProduction
or EnvStaging.

<a id="EnvExtension.IsStaging"></a>

#### func (*EnvExtension) IsStaging

```go
func (em *EnvExtension) IsStaging() bool
```

IsStaging reports whether the current environment is EnvStaging.

<a id="EnvExtension.IsTesting"></a>

#### func (*EnvExtension) IsTesting

```go
func (em *EnvExtension) IsTesting() bool
```

IsTesting reports whether the current environment is EnvTesting.

<a id="EnvExtension.Name"></a>

#### func (*EnvExtension) Name

```go
func (em *EnvExtension) Name() string
```

Name returns ExtensionName.

<a id="EnvExtension.PostLoad"></a>

#### func (*EnvExtension) PostLoad

```go
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.

<a id="EnvExtension.PreLoad"></a>

#### func (*EnvExtension) PreLoad

```go
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.

<a id="EnvOption"></a>

### type EnvOption

```go
type EnvOption func(*EnvExtension)
```

EnvOption configures an EnvExtension.

<a id="WithAllowedEnvs"></a>

#### func WithAllowedEnvs

```go
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.

<a id="WithConfigKey"></a>

#### func WithConfigKey

```go
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.

<a id="WithDefault"></a>

#### func WithDefault

```go
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.

<a id="WithEnvVarName"></a>

#### func WithEnvVarName

```go
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.

<a id="EnvProvider"></a>

### type EnvProvider

```go
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.

<a id="NewEnvProvider"></a>

#### func NewEnvProvider

```go
func NewEnvProvider(opts ...EnvProviderOption) *EnvProvider
```

NewEnvProvider returns an EnvProvider configured by opts.

<a id="EnvProvider.Load"></a>

#### func (*EnvProvider) Load

```go
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.

<a id="EnvProvider.Name"></a>

#### func (*EnvProvider) Name

```go
func (p *EnvProvider) Name() string
```

Name returns EnvProviderName.

<a id="EnvProviderOption"></a>

### type EnvProviderOption

```go
type EnvProviderOption func(*EnvProvider)
```

EnvProviderOption configures an EnvProvider.

<a id="WithEnvPrefix"></a>

#### func WithEnvPrefix

```go
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.

<a id="WithEnvSeparator"></a>

#### func WithEnvSeparator

```go
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: `__`.

<a id="WithoutEnvPrefix"></a>

#### func WithoutEnvPrefix

```go
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.

<a id="Environment"></a>

### type Environment

```go
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.

<a id="Extension"></a><a id="Extension.Name"></a><a id="Extension.PreLoad"></a><a id="Extension.PostLoad"></a>

### type Extension

```go
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.

<a id="JSONOption"></a>

### type JSONOption

```go
type JSONOption func(*JSONProvider)
```

JSONOption configures a JSONProvider.

<a id="WithJSONFileFS"></a>

#### func WithJSONFileFS

```go
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.

<a id="WithJSONFilePath"></a>

#### func WithJSONFilePath

```go
func WithJSONFilePath(filePath string) JSONOption
```

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

<a id="JSONProvider"></a>

### type JSONProvider

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

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

<a id="NewJSONProvider"></a>

#### func NewJSONProvider

```go
func NewJSONProvider(opts ...JSONOption) *JSONProvider
```

NewJSONProvider returns a JSONProvider configured by opts.

<a id="JSONProvider.Load"></a>

#### func (*JSONProvider) Load

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

Load reads the file.

<a id="JSONProvider.Name"></a>

#### func (*JSONProvider) Name

```go
func (p *JSONProvider) Name() string
```

Name returns "JSON".

<a id="Option"></a>

### type Option

```go
type Option func(*Config)
```

Option configures a Config.

<a id="WithExtension"></a>

#### func WithExtension

```go
func WithExtension(ext Extension) Option
```

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

<a id="WithProvider"></a>

#### func WithProvider

```go
func WithProvider(p Provider) Option
```

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

<a id="WithValidator"></a>

#### func WithValidator

```go
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().

<a id="WithoutEnvExtension"></a>

#### func WithoutEnvExtension

```go
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.

<a id="Provider"></a><a id="Provider.Name"></a><a id="Provider.Load"></a>

### type Provider

```go
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.

<a id="Validator"></a><a id="Validator.StructCtx"></a>

### type Validator

```go
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.
