1 Star 0 Fork 0

ziEgate / common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
config.go 2.01 KB
一键复制 编辑 原始数据 按行查看 历史
ziEgate 提交于 2022-05-22 09:43 . feat:增加InitConfig函数
package common
import (
"fmt"
"strings"
"github.com/spf13/viper"
)
func GetString(conf *viper.Viper, node, key string) string {
nodes := makeNodes(node)
nodes = append(nodes, key)
return conf.GetString(makeKey(nodes))
}
func GetSliceNodeString(conf *viper.Viper, nodes []string, key string) string {
nodes = append(nodes, key)
return conf.GetString(makeKey(nodes))
}
func GetInt(conf *viper.Viper, node, key string) int {
nodes := makeNodes(node)
nodes = append(nodes, key)
return conf.GetInt(makeKey(nodes))
}
func GetSliceNodeInt(conf *viper.Viper, nodes []string, key string) int {
nodes = append(nodes, key)
return conf.GetInt(makeKey(nodes))
}
func GetStringSlice(conf *viper.Viper, node, key string) []string {
nodes := makeNodes(node)
nodes = append(nodes, key)
return conf.GetStringSlice(makeKey(nodes))
}
func GetSliceNodeStringSlice(conf *viper.Viper, nodes []string, key string) []string {
nodes = append(nodes, key)
return conf.GetStringSlice(makeKey(nodes))
}
func GetBool(conf *viper.Viper, node, key string) bool {
nodes := makeNodes(node)
nodes = append(nodes, key)
return conf.GetBool(makeKey(nodes))
}
func GetSliceNodeBool(conf *viper.Viper, nodes []string, key string) bool {
nodes = append(nodes, key)
return conf.GetBool(makeKey(nodes))
}
func makeKey(keys []string) string {
k := make([]string, 0, len(keys))
for i := range keys {
if len(keys[i]) != 0 {
k = append(k, keys[i])
}
}
return strings.Join(k, ".")
}
func makeNodes(node string) []string {
nodes := make([]string, 0)
if _n := strings.Split(node, "."); len(_n) >= 1 {
nodes = append(nodes, _n...)
} else {
nodes = append(nodes, node)
}
return nodes
}
func InitConfig(configId, configPath string) (*viper.Viper, error) {
conf := viper.New()
conf.SetConfigType("toml")
conf.SetConfigName(strings.ToLower(configId))
conf.AddConfigPath(configPath)
err := conf.ReadInConfig()
if err != nil {
return nil, fmt.Errorf("initialize config error, ConfigId: %s, Error:%w", configId, err)
}
return conf, nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ziegate/common.git
git@gitee.com:ziegate/common.git
ziegate
common
common
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891