79 lines
1.6 KiB
Go
79 lines
1.6 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"reflect"
|
|
"sync"
|
|
|
|
"github.com/BurntSushi/toml"
|
|
)
|
|
|
|
var (
|
|
config map[string]interface{}
|
|
mu sync.Mutex
|
|
)
|
|
|
|
func loadConfig() {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
if _, err := toml.DecodeFile("config.toml", &config); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
}
|
|
func GetConfig() map[string]interface{} {
|
|
// mu.Lock()
|
|
// defer mu.Unlock()
|
|
// print(config)
|
|
if config == nil {
|
|
loadConfig()
|
|
}
|
|
return config
|
|
}
|
|
func ReloadConfig() {
|
|
loadConfig()
|
|
}
|
|
func ModifyConfig(key string, value interface{}) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
// 修改配置
|
|
config[key] = value
|
|
// fmt.Println("修改后的配置:")
|
|
// 将修改后的配置写回文件
|
|
file, err := os.Create("config.toml")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
defer file.Close()
|
|
|
|
encoder := toml.NewEncoder(file)
|
|
if err := encoder.Encode(config); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
}
|