64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/fsnotify/fsnotify"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type Config struct {
|
|
Url string `mapstructure:"url"`
|
|
Token string `mapstructure:"token"`
|
|
ThreadCount int `mapstructure:"thread-count"`
|
|
IsRunOnStart bool `mapstructure:"is-run-on-start"`
|
|
LookingPath string `mapstructure:"looking-path"`
|
|
}
|
|
|
|
var APPConfig Config
|
|
|
|
func InitConfig() {
|
|
// 设置默认配置
|
|
defaultConfig := Config{
|
|
Url: "http://127.0.0.1:8080",
|
|
Token: "",
|
|
ThreadCount: 10,
|
|
IsRunOnStart: false,
|
|
LookingPath: "",
|
|
}
|
|
viper.SetDefault("url", defaultConfig.Url)
|
|
viper.SetDefault("token", defaultConfig.Token)
|
|
viper.SetDefault("thread-count", defaultConfig.ThreadCount)
|
|
viper.SetDefault("is-run-on-start", defaultConfig.IsRunOnStart)
|
|
viper.SetDefault("looking-path", defaultConfig.LookingPath)
|
|
|
|
//设置配置文件名和路径 ./config.toml
|
|
viper.AddConfigPath(".")
|
|
viper.SetConfigName("config")
|
|
viper.SetConfigType("toml")
|
|
viper.SafeWriteConfig() //安全写入默认配置
|
|
|
|
//读取配置文件
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
fmt.Errorf("无法读取配置文件: %w", err)
|
|
}
|
|
if err := viper.Unmarshal(&APPConfig); err != nil {
|
|
fmt.Errorf("无法解析配置: %w", err)
|
|
}
|
|
|
|
viper.WatchConfig()
|
|
viper.OnConfigChange(func(e fsnotify.Event) {
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
fmt.Errorf("无法读取配置文件: %w", err)
|
|
}
|
|
if err := viper.Unmarshal(&APPConfig); err != nil {
|
|
fmt.Errorf("无法解析配置: %w", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func WriteConfig(key string, value any) {
|
|
viper.Set(key, value)
|
|
viper.WriteConfig()
|
|
}
|