/** * @Author: jager * @Email: lhj168os@gmail.com * @File: cfg * @Date: 2021/12/2 6:24 下午 * @package: cfg * @Version: v1.0.0 * * @Description: * */ package cfg import ( "github.com/jageros/hawox/logx" "github.com/spf13/pflag" "github.com/spf13/viper" "strings" "time" ) var ( QywxRobotUrl = "" DingTalkSecret = "" DingTalkRobotUrl = "" WxgzhAppid = "" WxgzhSecret = "" TianApiKey = "" UpdateDuration = time.Second * 60 // 默认一分钟 ThresholdValue float64 = 1 // 默认1% StockCodes = []string{"600905", "600032", "002531", "600733", "000825", "002939"} // 三峡能源, 浙江新能, 天顺风能, 北汽蓝谷, 太钢不锈, 长城证券 FundCodes = []string{"006229", "162412", "008359", "161725", "012314", "162719", "501057"} ) func load(v *viper.Viper) { QywxRobotUrl = v.GetString("qywxRobotUrl") DingTalkSecret = v.GetString("dingTalkSecret") DingTalkRobotUrl = v.GetString("dingTalkRobotUrl") WxgzhAppid = v.GetString("wxgzhAppid") WxgzhSecret = v.GetString("wxgzhSecret") TianApiKey = v.GetString("tianApiKey") updates := v.GetInt("updateSecond") if updates > 0 { UpdateDuration = time.Duration(updates) * time.Second } ThresholdValue = v.GetFloat64("thresholdValue") StockCodes = v.GetStringSlice("stock") FundCodes = v.GetStringSlice("fund") } func Init() error { pflag.String("c", "config.yaml", "config file") pflag.Parse() v := viper.New() err := v.BindPFlags(pflag.CommandLine) if err != nil { return err } path := v.GetString("c") var dir, fileName, fileType string // 配置文件路径不为空则读取配置文件, 即命令行有传入配置文件路径时 if path != "" { // 获取配置文件的后缀名 strs := strings.Split(path, ".") length := len(strs) if length < 2 { logx.Fatal("错误的配置文件路径") } fileType = strs[length-1] switch fileType { // 支持的文件类型yaml、json、 toml、hcl, ini case "yaml", "yml", "json", "toml", "hcl", "ini": fPath := strings.Replace(path, "."+fileType, "", -1) strs = strings.Split(fPath, "/") if len(strs) < 2 { fileName = strs[0] dir = "./" } else { fileName = strs[len(strs)-1] dir = strings.Join(strs[:len(strs)-1], "/") } //设置读取的配置文件 v.SetConfigName(fileName) //添加读取的配置文件路径 v.AddConfigPath(dir) //设置配置文件类型 v.SetConfigType(fileType) if err := v.ReadInConfig(); err != nil { logx.Fatalf("v.ReadInConfig err: %v", err) } default: // 其他类型抛出错误 logx.Fatal("错误的配置文件类型") } } load(v) return nil }