refactor:优化file包结构

This commit is contained in:
Mmx
2021-05-05 10:11:37 +08:00
parent 7ceb7169e5
commit 9c274d4364
2 changed files with 14 additions and 6 deletions

View File

@@ -23,7 +23,11 @@ func (*file) Exists(path string) bool {
return true return true
} }
func (*file) Read(path string, receiver interface{}) error { func (a *file) Read(path string) ([]byte, error) {
return ioutil.ReadFile(a.GetRootPath() + "/" + path)
}
func (*file) ReadJson(path string, receiver interface{}) error {
file, err := ioutil.ReadFile(path) file, err := ioutil.ReadFile(path)
if err != nil { if err != nil {
return err return err
@@ -31,12 +35,16 @@ func (*file) Read(path string, receiver interface{}) error {
return json.Unmarshal(file, receiver) return json.Unmarshal(file, receiver)
} }
func (*file) Write(path string, receiver interface{}) error { func (a *file) Write(path string, data []byte) error {
return ioutil.WriteFile(a.GetRootPath()+"/"+path, data, 700)
}
func (a *file) WriteJson(path string, receiver interface{}) error {
data, err := json.MarshalIndent(receiver, "", " ") data, err := json.MarshalIndent(receiver, "", " ")
if err != nil { if err != nil {
return err return err
} }
return ioutil.WriteFile(path, data, 700) return a.Write(path, data)
} }
func (*file) GetRootPath() string { func (*file) GetRootPath() string {

View File

@@ -9,9 +9,9 @@ import (
func init() { func init() {
//配置文件初始化 //配置文件初始化
Path := File.GetRootPath() + "/Config.json" Path := "Config.json"
if !File.Exists(Path) { if !File.Exists(Path) {
if err := File.Write(Path, &Modles.Config{ //默认值 if err := File.WriteJson(Path, &Modles.Config{ //默认值
From: Modles.LoginForm{ From: Modles.LoginForm{
Domain: "www.msftconnecttest.com", Domain: "www.msftconnecttest.com",
UserName: "", UserName: "",
@@ -32,7 +32,7 @@ func init() {
} }
var c Modles.Config var c Modles.Config
if err := File.Read(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)
} }