Add reflective struct-tag config loader
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>
This commit is contained in:
parent
3c806e6803
commit
c4ebd80669
15 changed files with 941 additions and 0 deletions
34
source.go
Normal file
34
source.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package conf
|
||||
|
||||
import "os"
|
||||
|
||||
// Source returns a string value for a key, or false if the key is not present.
|
||||
type Source interface {
|
||||
Lookup(key string) (string, bool)
|
||||
}
|
||||
|
||||
type envSource struct{}
|
||||
|
||||
func (envSource) Lookup(key string) (string, bool) {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return "", false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
// EnvSource reads from the process environment. Empty values are treated as absent.
|
||||
func EnvSource() Source { return envSource{} }
|
||||
|
||||
type mapSource map[string]string
|
||||
|
||||
func (m mapSource) Lookup(key string) (string, bool) {
|
||||
v, ok := m[key]
|
||||
if !ok || v == "" {
|
||||
return "", false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
// MapSource wraps a key/value map as a Source. The map is not copied.
|
||||
func MapSource(m map[string]string) Source { return mapSource(m) }
|
||||
Loading…
Add table
Add a link
Reference in a new issue