Skip to content

Commit

Permalink
feat:缺失Config属性回填
Browse files Browse the repository at this point in the history
  • Loading branch information
Mmx committed May 11, 2021
1 parent 022f1ac commit 8a82db3
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 17 deletions.
34 changes: 34 additions & 0 deletions Modles/config.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package Modles

import (
"Mmx/Modles/util"
"reflect"
)

type Settings struct {
QuitIfNetOk bool `json:"quit_if_net_ok"`
DemoMode bool `json:"demo_mode"`
Expand All @@ -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 changes: 19 additions & 0 deletions Modles/util/reflect.go
Original file line number Diff line number Diff line change
@@ -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
}
24 changes: 7 additions & 17 deletions Util/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,25 @@ import (
func init() {
//配置文件初始化
Path := "Config.json"
var c Modles.Config
if !File.Exists(Path) {
if err := File.WriteJson(Path, &Modles.Config{ //默认值
From: Modles.LoginForm{
Domain: "www.msftconnecttest.com",
UserName: "",
PassWord: "",
},
Meta: Modles.LoginMeta{
N: "200",
VType: "1",
Acid: "5",
Enc: "srun_bx1",
},
Settings: Modles.Settings{
Dns: "1.2.4.8",
},
}); err != nil {
if err := File.WriteJson(
Path,
c.FillDefault(),
); err != nil {
log.Println("创建配置文件失败:\n", err.Error())
os.Exit(1)
}
log.Println("已生成配置文件,请编辑 'Config.json' 然后重试")
os.Exit(0)
}

var c Modles.Config
if err := File.ReadJson(Path, &c); err != nil {
log.Println("读取配置文件失败:\n", err.Error())
os.Exit(1)
}

_ = File.WriteJson(Path, c.FillDefault())

Global.Config = &c
}

0 comments on commit 8a82db3

Please sign in to comment.