优化读取任意文件并解析

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类型