优化读取任意文件并解析

This commit is contained in:
白茶清欢 2023-08-15 12:06:29 +08:00
parent e6ad534a9a
commit 5c584bcb76
3 changed files with 16 additions and 8 deletions

20
file.go
View File

@ -13,6 +13,7 @@ import (
"io"
"net/http"
"os"
"path"
"path/filepath"
"strings"
@ -132,15 +133,17 @@ func (f *file) ReadTomlContent(filePath string, result interface{}) error {
//
// Date : 13:11 2022/7/2
func (f *file) ReadAnyFileContent(filePath string, receiver interface{}) error {
fileInfoArr := strings.Split(filePath, ".")
if len(fileInfoArr) < 2 {
return errors.New("未知的文件类型")
}
var (
parseFunc func(filePath string, receiver interface{}) error
)
fileExt := strings.ToLower(fileInfoArr[len(fileInfoArr)-1])
filePathArr := strings.Split(filePath, "#@#")
fileExt := ""
filePath = filePathArr[0]
if len(filePathArr) == 2 && len(filePathArr[1]) > 0 {
fileExt = strings.ToLower(filePathArr[1])
} else {
fileExt = strings.ToLower(path.Ext(filePath))
}
switch fileExt {
case consts.FileTypeJson:
parseFunc = f.ReadJSONContent
@ -150,6 +153,8 @@ func (f *file) ReadAnyFileContent(filePath string, receiver interface{}) error {
parseFunc = f.ReadYmlContent
case consts.FileTypeIni:
parseFunc = f.ReadIniContent
case consts.FileTypeToml:
parseFunc = f.ReadTomlContent
default:
return errors.New(fileExt + " 暂不支持当前格式的文件解析")
}
@ -190,7 +195,8 @@ func (f *file) ReadFileContent(filePath string) ([]byte, error) {
// Date : 10:37 下午 2021/4/26
func (f *file) IsFileExist(filePath string) (bool, bool) {
fileStat, err := os.Stat(filePath)
return nil == err || os.IsExist(err), (nil == err || os.IsExist(err)) && !fileStat.IsDir()
isFileExist := nil == err || os.IsExist(err)
return isFileExist, isFileExist && !fileStat.IsDir()
}
// GetFileMIMEType 获取本地文件的MIME类型

2
go.mod
View File

@ -9,4 +9,4 @@ require (
gopkg.in/yaml.v3 v3.0.1
)
require git.zhangdeman.cn/zhangdeman/consts v0.0.0-20230811030300-6f850372c88c // indirect
require git.zhangdeman.cn/zhangdeman/consts v0.0.0-20230815040024-2b12dd51d19b // indirect

2
go.sum
View File

@ -1,5 +1,7 @@
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20230811030300-6f850372c88c h1:Dan3iSVU6XTKt8r3/qixfPHPpfLZjkYlPmaJios7wtE=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20230811030300-6f850372c88c/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20230815040024-2b12dd51d19b h1:C7KftnLh7dOqzNRs5dn/9yqMDvuqMn5RCglvV6bY758=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20230815040024-2b12dd51d19b/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/util v0.0.0-20230810093304-ccb4045065c4 h1:MgZ2f1BkUtfP8D6uDX9S8o+V4wYUw76HlAw3xCH9epA=
git.zhangdeman.cn/zhangdeman/util v0.0.0-20230810093304-ccb4045065c4/go.mod h1:tPl6isAsRQLZrX8G3/8fCdhN4OcZypdmdHR/PDkd2PY=
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=