go-config/config.go
Zeev Diukman f3ca3f9d55 4
2025-03-06 22:50:03 +00:00

74 lines
1.4 KiB
Go

package config
import (
"strings"
"github.com/gookit/goutil/dump"
"github.com/spf13/viper"
)
type Config struct {
*viper.Viper
Keys Keys
}
type Keys []string
type Key string
type KeyPart string
type MapStringAny = map[string]any
func NewConfig(name string, configType string, path string) *Config {
c := &Config{}
c.Viper = viper.New()
c.SetConfigName(name)
c.SetConfigType(configType)
c.AddConfigPath(path)
return c
}
func (c *Config) Load() error {
err := c.ReadInConfig()
return err
}
func (c *Config) GetSubKeys(firstPart string, shouldDump bool) (string, Keys) {
subKeys := c.Sub(firstPart).AllKeys()
if shouldDump {
dump.Println(subKeys)
}
c.Keys = subKeys
return firstPart, subKeys
}
func (keys Keys) ForEach(fn func(i int, k Key)) {
for idx, key := range keys {
fn(idx, Key(key))
}
}
// func (k Key) ForEachPart(fn func(i int, p Key)) {
// for idx, key := range keys {
// fn(idx, Key(key))
// }
// }
func (k Key) GetKeyPartByLevel(level int) KeyPart {
return KeyPart(strings.Split(string(k), ".")[level])
}
func (k Key) ForEach(fn func(i int, p KeyPart, isFirst bool)) {
for idx, key := range strings.Split(string(k), ".") {
isFirst := false
if idx == 0 {
isFirst = true
}
fn(idx, KeyPart(key), isFirst)
}
}
// func (c *Config) GetByKey() error {
// func
// func (c *Config) ForEachByKey(fn func(key string, value any)) {
// for _, key := range c.() {
// fn(key, c.Get(key))
// }
// }