| 1 |
// Package structs implements a koanf.Provider that takes a struct and tag |
| 2 |
// and returns a nested config map (using fatih/structs) to provide it to koanf. |
| 3 |
package structs |
| 4 |
|
| 5 |
import ( |
| 6 |
"errors" |
| 7 |
|
| 8 |
"github.com/fatih/structs" |
| 9 |
|
| 10 |
"github.com/knadh/koanf/maps" |
| 11 |
) |
| 12 |
|
| 13 |
// Structs implements a structs provider. |
| 14 |
type Structs struct { |
| 15 |
s any |
| 16 |
tag string |
| 17 |
delim string |
| 18 |
} |
| 19 |
|
| 20 |
// Provider returns a provider that takes a struct and a struct tag |
| 21 |
// and uses structs to parse and provide it to koanf. |
| 22 |
func Provider(s any, tag string) *Structs { |
| 23 |
return &Structs{s: s, tag: tag} |
| 24 |
} |
| 25 |
|
| 26 |
// ProviderWithDelim returns a provider that takes a struct and a struct tag |
| 27 |
// along with a delim and uses structs to parse and provide it to koanf. |
| 28 |
func ProviderWithDelim(s any, tag, delim string) *Structs { |
| 29 |
return &Structs{s: s, tag: tag, delim: delim} |
| 30 |
} |
| 31 |
|
| 32 |
// ReadBytes is not supported by the structs provider. |
| 33 |
func (s *Structs) ReadBytes() ([]byte, error) { |
| 34 |
return nil, errors.New("structs provider does not support this method") |
| 35 |
} |
| 36 |
|
| 37 |
// Read reads the struct and returns a nested config map. |
| 38 |
func (s *Structs) Read() (map[string]any, error) { |
| 39 |
ns := structs.New(s.s) |
| 40 |
ns.TagName = s.tag |
| 41 |
|
| 42 |
out := ns.Map() |
| 43 |
|
| 44 |
if s.delim != "" { |
| 45 |
out = maps.Unflatten(out, s.delim) |
| 46 |
} |
| 47 |
|
| 48 |
return out, nil |
| 49 |
} |