Implements conf.Load to populate tagged structs from a chain of Sources (env, .env, YAML/JSON/TOML, custom). Supports default values, slice separators, nested structs, pointer fields, and a Validator hook. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
33 lines
728 B
Go
33 lines
728 B
Go
package conf
|
|
|
|
import (
|
|
"io"
|
|
"os"
|
|
|
|
"git.juancwu.dev/juancwu/errx"
|
|
"github.com/goccy/go-yaml"
|
|
)
|
|
|
|
// YAMLFile loads a YAML document and exposes it as a flat key->string Source.
|
|
func YAMLFile(path string) (Source, error) {
|
|
const op = "conf.YAMLFile"
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, errx.Wrapf(op, err, "open %s", path)
|
|
}
|
|
defer f.Close()
|
|
return YAMLReader(f)
|
|
}
|
|
|
|
// YAMLReader is YAMLFile for an arbitrary reader.
|
|
func YAMLReader(r io.Reader) (Source, error) {
|
|
const op = "conf.YAMLReader"
|
|
var raw map[string]any
|
|
if err := yaml.NewDecoder(r).Decode(&raw); err != nil {
|
|
if err == io.EOF {
|
|
return MapSource(nil), nil
|
|
}
|
|
return nil, errx.Wrap(op, err)
|
|
}
|
|
return MapSource(flatten(raw)), nil
|
|
}
|