go-bot/config/config.go

84 lines
1.8 KiB
Go
Raw Normal View History

2024-04-01 09:42:29 +08:00
package config
import (
"fmt"
"os"
"reflect"
"sync"
2024-04-01 09:42:29 +08:00
"github.com/BurntSushi/toml"
)
2024-04-01 09:42:29 +08:00
var (
config map[string]interface{}
mu sync.RWMutex
once sync.Once
)
// loadConfig 加载配置文件
func loadConfig() error {
_, err := toml.DecodeFile("config.toml", &config)
return err
}
// GetConfig 获取配置,使用 sync.Once 确保只加载一次
func GetConfig() map[string]interface{} {
once.Do(func() {
mu.Lock()
defer mu.Unlock()
if err := loadConfig(); err != nil {
fmt.Printf("加载配置文件失败: %v\n", err)
os.Exit(1)
}
})
return config
2024-04-01 09:42:29 +08:00
}
// ReloadConfig 重新加载配置文件
func ReloadConfig() error {
mu.Lock()
defer mu.Unlock()
return loadConfig()
}
// ModifyConfig 修改配置并写回文件
func ModifyConfig(key string, value interface{}) error {
mu.Lock()
defer mu.Unlock()
config[key] = value
file, err := os.Create("config.toml")
if err != nil {
return err
}
defer file.Close()
encoder := toml.NewEncoder(file)
return encoder.Encode(config)
}
// PrintConfig 递归打印配置内容
func PrintConfig(m map[string]interface{}, indent string) {
for key, value := range m {
switch v := value.(type) {
case map[string]interface{}:
fmt.Printf("%s%s (type: %s):\n", indent, key, reflect.TypeOf(v))
PrintConfig(v, indent+" ")
case []interface{}:
fmt.Printf("%s%s:\n", indent, key)
for i, item := range v {
switch itemValue := item.(type) {
case map[string]interface{}:
fmt.Printf("%s [%d] (type: %s):\n", indent, i, reflect.TypeOf(itemValue))
PrintConfig(itemValue, indent+" ")
default:
fmt.Printf("%s [%d] (type: %s): %v\n", indent, i, reflect.TypeOf(itemValue), item)
}
}
default:
fmt.Printf("%s%s (type: %s): %v\n", indent, key, reflect.TypeOf(value), value)
}
}
}