diff --git a/file.go b/file.go index 28ea6dd..39e12a7 100644 --- a/file.go +++ b/file.go @@ -8,9 +8,14 @@ package command import ( + "bytes" + "encoding/json" "errors" + "io" "os" "strings" + + "gopkg.in/yaml.v2" ) // File ... @@ -143,3 +148,53 @@ func (f *fileOperate) Open() error { func (f *fileOperate) GetFileHandler() *os.File { return f.fileHandler } + +// Read 读取文件内容 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 15:39 2022/5/22 +func (f *fileOperate) Read() ([]byte, error) { + if nil == f.fileHandler { + if err := f.Open(); nil != err { + return nil, errors.New("文件打开失败 : " + err.Error()) + } + } + return io.ReadAll(f.fileHandler) +} + +// ReadForJSON 读取文件, 并解析为json +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 15:40 2022/5/22 +func (f *fileOperate) ReadForJSON(receiver interface{}) error { + var ( + content []byte + err error + ) + if content, err = f.Read(); nil != err { + return err + } + decoder := json.NewDecoder(bytes.NewReader(content)) + decoder.UseNumber() + return decoder.Decode(receiver) +} + +// ReadForYaml 读取yaml文件, 并解析到结构体 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 15:43 2022/5/22 +func (f *fileOperate) ReadForYaml(receiver interface{}) error { + var ( + content []byte + err error + ) + if content, err = f.Read(); nil != err { + return err + } + decoder := yaml.NewDecoder(bytes.NewReader(content)) + decoder.SetStrict(true) + return decoder.Decode(receiver) +} diff --git a/go.mod b/go.mod index 8904d5b..b42dd56 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module git.zhangdeman.cn/zhangdeman/command go 1.17 + +require gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index e69de29..7534661 100644 --- a/go.sum +++ b/go.sum @@ -0,0 +1,3 @@ +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=