feat: 支持多类型配置文件

This commit is contained in:
Mmx233
2022-01-21 22:39:05 +08:00
parent 04a9eb8291
commit 30878bd990
4 changed files with 120 additions and 34 deletions

View File

@@ -3,7 +3,8 @@ package global
import (
"github.com/Mmx233/BitSrunLoginGo/models"
"github.com/Mmx233/BitSrunLoginGo/v1/transfer"
"github.com/Mmx233/config"
"github.com/Mmx233/tool"
"github.com/spf13/viper"
"log"
"os"
"time"
@@ -13,42 +14,59 @@ var Config srunModels.Config
var Timeout time.Duration
func readConfig() error {
//配置文件默认值
viper.SetDefault("form", srunTransfer.LoginForm{
Domain: "www.msftconnecttest.com",
UserType: "cmcc",
})
viper.SetDefault("meta", srunTransfer.LoginMeta{
N: "200",
Type: "1",
Acid: "5",
Enc: "srun_bx1",
})
viper.SetDefault("settings", srunModels.Settings{
Timeout: 5,
Daemon: srunModels.Daemon{
Path: ".autoLogin",
},
Guardian: srunModels.Guardian{
Duration: 300,
},
})
//生成配置文件
if !tool.File.Exists(Flags.Path) {
e := viper.WriteConfigAs(Flags.Path)
if e != nil {
log.Println("生成配置文件失败:", e)
return e
}
log.Println("已生成配置文件,请编辑 '" + Flags.Path + "' 然后重试")
os.Exit(0)
}
//读取配置文件
viper.SetConfigFile(Flags.Path)
if e := viper.ReadInConfig(); e != nil {
log.Println("读取配置文件失败:", e)
return e
}
if e := viper.Unmarshal(&Config); e != nil {
log.Println("解析配置文件失败:", e)
return e
}
_ = viper.WriteConfig()
return nil
}
func init() {
initFlags()
//配置文件初始化
if e := config.Load(config.Options{
Config: &Config,
Default: &srunModels.Config{
Form: srunTransfer.LoginForm{
Domain: "www.msftconnecttest.com",
UserType: "cmcc",
},
Meta: srunTransfer.LoginMeta{
N: "200",
Type: "1",
Acid: "5",
Enc: "srun_bx1",
},
Settings: srunModels.Settings{
Timeout: 5,
Daemon: srunModels.Daemon{
Path: ".autoLogin",
},
Guardian: srunModels.Guardian{
Duration: 300,
},
},
},
Path: Flags.Path,
FillDefault: false,
Overwrite: true,
}); e != nil {
if config.IsNew(e) {
log.Println("已生成配置文件,请编辑 '" + Flags.Path + "' 然后重试")
os.Exit(0)
}
log.Println("读取配置文件失败:\n", e.Error())
if readConfig() != nil {
os.Exit(1)
}