diff --git a/go.mod b/go.mod index 2528150..e126830 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( github.com/tidwall/gjson v1.6.8 github.com/tidwall/pretty v1.1.0 // indirect go.uber.org/zap v1.16.0 + gopkg.in/yaml.v2 v2.4.0 // indirect gorm.io/driver/mysql v1.0.4 gorm.io/gorm v1.20.12 ) diff --git a/go.sum b/go.sum index ad597d1..38807c6 100644 --- a/go.sum +++ b/go.sum @@ -203,6 +203,8 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gorm.io/driver/mysql v1.0.4 h1:TATTzt+kR+IV0+h3iUB3dHUe8omCvQ0rOkmfCsUBohk= diff --git a/util/file.go b/util/file.go index b26fac7..9f8b987 100644 --- a/util/file.go +++ b/util/file.go @@ -8,8 +8,12 @@ package util import ( + "io/ioutil" "os" "strings" + + "github.com/pkg/errors" + yml "gopkg.in/yaml.v2" ) // GetProjectPath 获取项目路径(可执行文件所在目录) @@ -30,3 +34,54 @@ func GetProjectPath() (string, error) { } return rootPath, nil } + +// ReadYmlConfig 读取yml配置问价,并解析到指定的结构体中 +// +// Author : go_developer@163.com<张德满> +// +// Date : 10:35 下午 2021/4/26 +func ReadYmlConfig(filePath string, result interface{}) error { + if nil == result { + return errors.New("接收读取结果的数据指针为NIL") + } + var ( + fileContent []byte + err error + ) + if fileContent, err = ReadFileContent(filePath); nil != err { + return err + } + return yml.Unmarshal(fileContent, result) +} + +// ReadFileContent 读取文件内容 +// +// Author : go_developer@163.com<张德满> +// +// Date : 10:37 下午 2021/4/26 +func ReadFileContent(filePath string) ([]byte, error) { + if exist, isFile := IsFileExist(filePath); !exist || !isFile { + //文件不存在或者是一个目录 + return nil, errors.New(filePath + " 文件不存在或者是一个目录!") + } + //打开文件 + var ( + f *os.File + err error + ) + if f, err = os.Open(filePath); nil != err { + return nil, err + } + + return ioutil.ReadAll(f) +} + +// IsFileExist 判断文件是否存在 +// +// Author : go_developer@163.com<张德满> +// +// Date : 10:37 下午 2021/4/26 +func IsFileExist(filePath string) (bool, bool) { + f, err := os.Stat(filePath) + return nil == err || os.IsExist(err), (nil == err || os.IsExist(err)) && !f.IsDir() +}