Эх сурвалжийг харах

增加了 可以设置多个配置文件

fly 1 жил өмнө
parent
commit
79dc3fc236

+ 2 - 9
config/config.go

@@ -4,19 +4,13 @@ import (
 	"github.com/spf13/viper"
 )
 
-type any interface{}
-
 var (
 	defaultName       = "config"
 	defaultConfigType = "yaml"
 	defaultPath       = "."
 )
 
-//func init() {
-//	Init()
-//}
-
-func Init() {
+func Default() {
 	//引入viper配置文件
 	viper.SetConfigName(defaultName) //defaultName := lib.AppName()
 	viper.SetConfigType(defaultConfigType)
@@ -59,9 +53,8 @@ func GetFloat(module string, key string) float64 {
 
 func GetStringSlice(module string, key string) []string {
 	return viper.GetStringSlice(module + "." + key)
-
 }
 
 func Set(module, key string, value any) {
-	viper.Set(module+"."+key, key)
+	viper.Set(module+"."+key, value)
 }

+ 1 - 1
config/config_test.go

@@ -14,7 +14,7 @@ func TestInit(t *testing.T) {
 	}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
-			Init()
+			Default()
 			t.Log(tt)
 			Store()
 		})

+ 54 - 0
config/object.go

@@ -0,0 +1,54 @@
+package config
+
+import "github.com/spf13/viper"
+
+type config struct {
+	viper *viper.Viper
+}
+
+func NewConfig(name, suffix, path string) *config {
+	var c config
+
+	c.viper = viper.New()
+	c.viper.SetConfigName(name) //defaultName := lib.AppName()
+	c.viper.SetConfigType(suffix)
+	c.viper.AddConfigPath(path)
+
+	return &c
+}
+
+func (c *config) Load() error {
+	return c.viper.ReadInConfig()
+}
+
+func (c *config) Store() error {
+	return c.viper.SafeWriteConfig()
+}
+
+func (c *config) Register(module, key string, value any) {
+	c.viper.SetDefault(module+"."+key, value)
+}
+
+func (c *config) GetBool(module, key string) bool {
+	return c.viper.GetBool(module + "." + key)
+}
+
+func (c *config) GetString(module, key string) string {
+	return c.viper.GetString(module + "." + key)
+}
+
+func (c *config) GetInt(module, key string) int {
+	return c.viper.GetInt(module + "." + key)
+}
+
+func (c *config) GetFloat(module, key string) float64 {
+	return c.viper.GetFloat64(module + "." + key)
+}
+
+func (c *config) GetStringSlice(module string, key string) []string {
+	return viper.GetStringSlice(module + "." + key)
+}
+
+func (c *config) Set(module, key string, value any) {
+	viper.Set(module+"."+key, value)
+}