89 lines
1.6 KiB
Go
89 lines
1.6 KiB
Go
package utils
|
||
|
||
import (
|
||
"crypto/md5"
|
||
"encoding/hex"
|
||
"fmt"
|
||
"git.hpds.cc/Component/logging"
|
||
"go.uber.org/zap"
|
||
"io"
|
||
"os"
|
||
"path"
|
||
"path/filepath"
|
||
"strings"
|
||
)
|
||
|
||
func CopyFile(src, dst string) error {
|
||
sourceFileStat, err := os.Stat(src)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
if !sourceFileStat.Mode().IsRegular() {
|
||
return fmt.Errorf("%s is not a regular file", src)
|
||
}
|
||
|
||
source, err := os.Open(src)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
defer func(source *os.File) {
|
||
_ = source.Close()
|
||
}(source)
|
||
|
||
destination, err := os.Create(dst)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
defer func(destination *os.File) {
|
||
_ = destination.Close()
|
||
}(destination)
|
||
_, err = io.Copy(destination, source)
|
||
return err
|
||
}
|
||
|
||
func PathExists(path string) bool {
|
||
_, err := os.Stat(path)
|
||
if err == nil {
|
||
return true
|
||
}
|
||
if os.IsNotExist(err) {
|
||
return false
|
||
}
|
||
return false
|
||
}
|
||
|
||
// ReadFile 读取到file中,再利用ioutil将file直接读取到[]byte中, 这是最优
|
||
func ReadFile(fn string) []byte {
|
||
f, err := os.Open(fn)
|
||
if err != nil {
|
||
logging.L().Error("Read File", zap.String("File Name", fn), zap.Error(err))
|
||
return nil
|
||
}
|
||
defer func(f *os.File) {
|
||
_ = f.Close()
|
||
}(f)
|
||
|
||
fd, err := io.ReadAll(f)
|
||
if err != nil {
|
||
logging.L().Error("Read File To buff", zap.String("File Name", fn), zap.Error(err))
|
||
return nil
|
||
}
|
||
|
||
return fd
|
||
}
|
||
|
||
func GetFileName(fn string) string {
|
||
fileType := path.Ext(fn)
|
||
return strings.TrimSuffix(fn, fileType)
|
||
}
|
||
func GetFileNameAndExt(fn string) string {
|
||
_, fileName := filepath.Split(fn)
|
||
return fileName
|
||
}
|
||
func GetFileMd5(data []byte) string {
|
||
hash := md5.New()
|
||
hash.Write(data)
|
||
return hex.EncodeToString(hash.Sum(nil))
|
||
}
|