d4cc335fbf
- 将全局变量 isRun 移动到 App 结构体内部作为实例字段 - 在 config.go 中定义配置键名为常量,提高代码可维护性 - 使用结构体实例字段替代全局变量管理上传状态 - 修改 StartLooking 函数中的上下文取消处理逻辑 - 移除上传程序退出日志的重复记录
76 lines
2.1 KiB
Go
76 lines
2.1 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"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
|
|
|
|
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) {
|
|
viper.Set(key, value)
|
|
viper.WriteConfig()
|
|
}
|