Files
dypid-client/config/config.go
YGXB_net 2f5708fbc2
All checks were successful
构建上传工具 / build-tool (push) Successful in 4m1s
feat(config): 添加文件并发处理配置和停止功能
2025-10-15 18:12:47 +08:00

67 lines
1.8 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"`
HandleFileCount int `mapstructure:"handle-file-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,
HandleFileCount: 50,
IsRunOnStart: false,
LookingPath: "",
}
viper.SetDefault("url", defaultConfig.Url)
viper.SetDefault("token", defaultConfig.Token)
viper.SetDefault("thread-count", defaultConfig.ThreadCount)
viper.SetDefault("handle-file-count", defaultConfig.HandleFileCount)
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()
}