增加文件的读取与解析操作

This commit is contained in:
白茶清欢 2022-05-22 15:46:44 +08:00
parent da134e32a1
commit c3c29411dc
3 changed files with 60 additions and 0 deletions

55
file.go
View File

@ -8,9 +8,14 @@
package command package command
import ( import (
"bytes"
"encoding/json"
"errors" "errors"
"io"
"os" "os"
"strings" "strings"
"gopkg.in/yaml.v2"
) )
// File ... // File ...
@ -143,3 +148,53 @@ func (f *fileOperate) Open() error {
func (f *fileOperate) GetFileHandler() *os.File { func (f *fileOperate) GetFileHandler() *os.File {
return f.fileHandler 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)
}

2
go.mod
View File

@ -1,3 +1,5 @@
module git.zhangdeman.cn/zhangdeman/command module git.zhangdeman.cn/zhangdeman/command
go 1.17 go 1.17
require gopkg.in/yaml.v2 v2.4.0 // indirect

3
go.sum
View File

@ -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=