4addc29b2c
- 引入 sync.Mutex 确保配置访问的线程安全性 - 在 WriteConfig 函数中实现读写锁定机制 - 防止多协程同时修改配置导致的数据竞争问题
80 lines
2.1 KiB
Go
80 lines
2.1 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
|
|
"github.com/fsnotify/fsnotify"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type Config struct {
|
|
Url string `json:"url" mapstructure:"url"`
|
|
Token string `json:"token" mapstructure:"token"`
|
|
ThreadCount int `json:"thread_count" mapstructure:"thread-count"`
|
|
HandleFileCount int `json:"handle_file_count" mapstructure:"handle-file-count"`
|
|
IsRunOnStart bool `json:"is_run_on_start" mapstructure:"is-run-on-start"`
|
|
CheckDir string `json:"check_dir" mapstructure:"check-dir"`
|
|
}
|
|
|
|
var APPConfig Config
|
|
var configMu sync.Mutex
|
|
|
|
const (
|
|
Url = "url"
|
|
Token = "token"
|
|
ThreadCount = "thread-count"
|
|
HandleFileCount = "handle-file-count"
|
|
IsRunOnStart = "is-run-on-start"
|
|
CheckDir = "check-dir"
|
|
)
|
|
|
|
func InitConfig() {
|
|
// 设置默认配置
|
|
defaultConfig := Config{
|
|
Url: "http://127.0.0.1:8080",
|
|
Token: "",
|
|
ThreadCount: 10,
|
|
HandleFileCount: 25,
|
|
IsRunOnStart: false,
|
|
CheckDir: "",
|
|
}
|
|
viper.SetDefault(Url, defaultConfig.Url)
|
|
viper.SetDefault(Token, defaultConfig.Token)
|
|
viper.SetDefault(ThreadCount, defaultConfig.ThreadCount)
|
|
viper.SetDefault(HandleFileCount, defaultConfig.HandleFileCount)
|
|
viper.SetDefault(IsRunOnStart, defaultConfig.IsRunOnStart)
|
|
viper.SetDefault(CheckDir, defaultConfig.CheckDir)
|
|
|
|
//设置配置文件名和路径 ./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) {
|
|
configMu.Lock()
|
|
viper.Set(key, value)
|
|
viper.WriteConfig()
|
|
configMu.Unlock()
|
|
}
|