From 9a93794f12c2119eb8e0524d872d7fdea86ac9f4 Mon Sep 17 00:00:00 2001 From: Zeev Diukman Date: Wed, 5 Mar 2025 16:35:12 +0000 Subject: [PATCH] 2 --- config.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/config.go b/config.go index 7ff9e66..79615d7 100644 --- a/config.go +++ b/config.go @@ -1,7 +1,73 @@ package config -import "github.com/spf13/viper" +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 + +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)) +// } +// }