forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/knadh/koanf/providers/structs/structs.go

71 lines
1.3 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
// Package structs implements a koanf.Provider that takes a struct and tag
2024-02-18 10:42:21 +00:00
// and returns a nested config map (using fatih/structs) to provide it to koanf.
2024-02-18 10:42:21 +00:00
package structs
import (
"errors"
"github.com/fatih/structs"
"github.com/knadh/koanf/maps"
)
// Structs implements a structs provider.
2024-02-18 10:42:21 +00:00
type Structs struct {
s interface{}
tag string
2024-02-18 10:42:21 +00:00
delim string
}
// Provider returns a provider that takes a takes a struct and a struct tag
2024-02-18 10:42:21 +00:00
// and uses structs to parse and provide it to koanf.
2024-02-18 10:42:21 +00:00
func Provider(s interface{}, tag string) *Structs {
2024-02-18 10:42:21 +00:00
return &Structs{s: s, tag: tag}
2024-02-18 10:42:21 +00:00
}
// ProviderWithDelim returns a provider that takes a takes a struct and a struct tag
2024-02-18 10:42:21 +00:00
// along with a delim and uses structs to parse and provide it to koanf.
2024-02-18 10:42:21 +00:00
func ProviderWithDelim(s interface{}, tag, delim string) *Structs {
2024-02-18 10:42:21 +00:00
return &Structs{s: s, tag: tag, delim: delim}
2024-02-18 10:42:21 +00:00
}
// ReadBytes is not supported by the structs provider.
2024-02-18 10:42:21 +00:00
func (s *Structs) ReadBytes() ([]byte, error) {
2024-02-18 10:42:21 +00:00
return nil, errors.New("structs provider does not support this method")
2024-02-18 10:42:21 +00:00
}
// Read reads the struct and returns a nested config map.
2024-02-18 10:42:21 +00:00
func (s *Structs) Read() (map[string]interface{}, error) {
2024-02-18 10:42:21 +00:00
ns := structs.New(s.s)
2024-02-18 10:42:21 +00:00
ns.TagName = s.tag
out := ns.Map()
if s.delim != "" {
2024-02-18 10:42:21 +00:00
out = maps.Unflatten(out, s.delim)
2024-02-18 10:42:21 +00:00
}
return out, nil
2024-02-18 10:42:21 +00:00
}