From c3c29411dc7d517b0a4a63823c9b26543b63da02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Sun, 22 May 2022 15:46:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=96=87=E4=BB=B6=E7=9A=84?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E4=B8=8E=E8=A7=A3=E6=9E=90=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- file.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 2 ++ go.sum | 3 +++ 3 files changed, 60 insertions(+) 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=