2024-04-01 09:42:29 +08:00
|
|
|
package config
|
|
|
|
|
2024-04-03 21:53:57 +08:00
|
|
|
import (
|
2024-06-30 21:56:34 +08:00
|
|
|
"fmt"
|
2024-07-01 10:05:42 +08:00
|
|
|
"os"
|
2024-06-30 21:56:34 +08:00
|
|
|
"reflect"
|
2024-06-30 16:12:26 +08:00
|
|
|
"sync"
|
2024-04-01 09:42:29 +08:00
|
|
|
|
2024-04-03 21:53:57 +08:00
|
|
|
"github.com/BurntSushi/toml"
|
|
|
|
)
|
2024-04-01 09:42:29 +08:00
|
|
|
|
2024-06-30 16:12:26 +08:00
|
|
|
var (
|
|
|
|
config map[string]interface{}
|
2024-07-01 10:05:42 +08:00
|
|
|
mu sync.Mutex
|
2024-06-30 16:12:26 +08:00
|
|
|
)
|
2024-04-03 21:53:57 +08:00
|
|
|
|
2024-06-30 16:12:26 +08:00
|
|
|
func loadConfig() {
|
2024-07-01 10:32:56 +08:00
|
|
|
// mu.Lock()
|
|
|
|
// defer mu.Unlock()
|
2024-04-03 21:53:57 +08:00
|
|
|
|
2024-06-30 16:12:26 +08:00
|
|
|
if _, err := toml.DecodeFile("config.toml", &config); err != nil {
|
|
|
|
panic(err)
|
2024-04-03 21:53:57 +08:00
|
|
|
}
|
2024-06-30 16:12:26 +08:00
|
|
|
|
|
|
|
}
|
|
|
|
func GetConfig() map[string]interface{} {
|
2024-07-01 10:32:56 +08:00
|
|
|
mu.Lock()
|
|
|
|
defer mu.Unlock()
|
2024-06-30 21:56:34 +08:00
|
|
|
// print(config)
|
2024-07-01 10:05:42 +08:00
|
|
|
if config == nil {
|
|
|
|
loadConfig()
|
|
|
|
}
|
2024-06-30 16:12:26 +08:00
|
|
|
return config
|
2024-04-01 09:42:29 +08:00
|
|
|
}
|
2024-07-01 10:05:42 +08:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
2024-06-30 21:56:34 +08:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|