feat:缺失Config属性回填

This commit is contained in:
Mmx
2021-05-11 12:43:54 +08:00
parent 022f1ac965
commit 8a82db3422
3 changed files with 60 additions and 17 deletions

View File

@@ -1,5 +1,10 @@
package Modles package Modles
import (
"Mmx/Modles/util"
"reflect"
)
type Settings struct { type Settings struct {
QuitIfNetOk bool `json:"quit_if_net_ok"` QuitIfNetOk bool `json:"quit_if_net_ok"`
DemoMode bool `json:"demo_mode"` DemoMode bool `json:"demo_mode"`
@@ -25,3 +30,32 @@ func (a *Config) Generate() *LoginInfo {
}, },
} }
} }
func (a *Config) FillDefault() *Config {
var m = map[interface{}]map[string]interface{}{
&a.From: {
"Domain": "www.msftconnecttest.com",
},
&a.Meta: {
"N": "200",
"VType": "1",
"Acid": "5",
"Enc": "srun_bx1",
},
&a.Settings: {
"Dns": "1.2.4.8",
},
}
for q, w := range m {
t := reflect.ValueOf(q).Elem()
for k, v := range w {
tt := t.FieldByName(k)
if util.Reflect.IsEmpty(tt) {
tt.Set(reflect.ValueOf(v))
}
}
}
return a
}

19
Modles/util/reflect.go Normal file
View File

@@ -0,0 +1,19 @@
package util
import "reflect"
type reflectR struct{}
var Reflect reflectR
func (*reflectR) IsEmpty(v reflect.Value) bool {
switch v.Kind() {
case reflect.Bool:
return !v.Bool()
case reflect.String:
return v.String() == ""
default:
panic("未设定值")
}
return false
}

View File

@@ -10,23 +10,12 @@ import (
func init() { func init() {
//配置文件初始化 //配置文件初始化
Path := "Config.json" Path := "Config.json"
var c Modles.Config
if !File.Exists(Path) { if !File.Exists(Path) {
if err := File.WriteJson(Path, &Modles.Config{ //默认值 if err := File.WriteJson(
From: Modles.LoginForm{ Path,
Domain: "www.msftconnecttest.com", c.FillDefault(),
UserName: "", ); err != nil {
PassWord: "",
},
Meta: Modles.LoginMeta{
N: "200",
VType: "1",
Acid: "5",
Enc: "srun_bx1",
},
Settings: Modles.Settings{
Dns: "1.2.4.8",
},
}); err != nil {
log.Println("创建配置文件失败:\n", err.Error()) log.Println("创建配置文件失败:\n", err.Error())
os.Exit(1) os.Exit(1)
} }
@@ -34,11 +23,12 @@ func init() {
os.Exit(0) os.Exit(0)
} }
var c Modles.Config
if err := File.ReadJson(Path, &c); err != nil { if err := File.ReadJson(Path, &c); err != nil {
log.Println("读取配置文件失败:\n", err.Error()) log.Println("读取配置文件失败:\n", err.Error())
os.Exit(1) os.Exit(1)
} }
_ = File.WriteJson(Path, c.FillDefault())
Global.Config = &c Global.Config = &c
} }