jsonsetting - skynocover/Wiki-for-GoLang GitHub Wiki
json setting and database
// LoadConfiguration 載入設定檔
func LoadConfiguration(filePath string) error {
newconfig := func(newPath string) error {
User = user{FilePath: filePath, Account: "admin", Password: "123456"}
User.Save()
return errors.New("Initial the new config")
}
if _, err := os.Stat(filePath); err != nil {
return newconfig(filePath)
}
content, err := ioutil.ReadFile(filePath)
if err != nil {
return newconfig(filePath)
}
err = json.Unmarshal(content, &User)
if err != nil {
return newconfig(filePath)
}
User.FilePath = filePath
return nil
}
// Save 儲存設定檔
func (c *user) Save() error {
content, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
err = ioutil.WriteFile(c.FilePath, content, os.ModePerm)
if err != nil {
return err
}
return nil
}
//修改並儲存設定檔
globals.User.Password = user.NewPassword
if err := globals.User.Save(); err != nil {
ctx.JSON(iris.Map{
"errorCode": 1003,
"errorMessage": fmt.Sprintf("User save fail, err: %v", err),
})
return
}
{
"filePath": "user.json",
"account": "admin",
"password": "123456"
}