增加文件的读取与解析操作
This commit is contained in:
parent
da134e32a1
commit
c3c29411dc
55
file.go
55
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)
|
||||
}
|
||||
|
2
go.mod
2
go.mod
@ -1,3 +1,5 @@
|
||||
module git.zhangdeman.cn/zhangdeman/command
|
||||
|
||||
go 1.17
|
||||
|
||||
require gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
|
Loading…
Reference in New Issue
Block a user