From 3eb103423f85fb2af1f5ff91432e30417551e313 Mon Sep 17 00:00:00 2001 From: liuxiaolong <736321739@qq.com> Date: 星期五, 20 十二月 2019 18:52:32 +0800 Subject: [PATCH] fix --- extend/util/util.go | 117 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 117 insertions(+), 0 deletions(-) diff --git a/extend/util/util.go b/extend/util/util.go index 224d086..3e74a89 100644 --- a/extend/util/util.go +++ b/extend/util/util.go @@ -1,8 +1,12 @@ package util import ( + "archive/tar" "archive/zip" "bytes" + "compress/gzip" + "crypto/md5" + "encoding/hex" "encoding/json" "image" "io" @@ -298,6 +302,103 @@ return nil } +//鍘嬬缉 浣跨敤gzip鍘嬬缉鎴恡ar.gz +func TarCompress(files []*os.File, dest string) error { + d, _ := os.Create(dest) + defer d.Close() + gw := gzip.NewWriter(d) + defer gw.Close() + tw := tar.NewWriter(gw) + defer tw.Close() + for _, file := range files { + err := gzipCompress(file, "", tw) + if err != nil { + return err + } + } + return nil +} + +func gzipCompress(file *os.File, prefix string, tw *tar.Writer) error { + info, err := file.Stat() + if err != nil { + return err + } + if info.IsDir() { + prefix = prefix + "/" + info.Name() + fileInfos, err := file.Readdir(-1) + if err != nil { + return err + } + for _, fi := range fileInfos { + f, err := os.Open(file.Name() + "/" + fi.Name()) + if err != nil { + return err + } + err = gzipCompress(f, prefix, tw) + if err != nil { + return err + } + } + } else { + header, err := tar.FileInfoHeader(info, "") + header.Name = prefix + "/" + header.Name + if err != nil { + return err + } + err = tw.WriteHeader(header) + if err != nil { + return err + } + _, err = io.Copy(tw, file) + file.Close() + if err != nil { + return err + } + } + return nil +} + +//瑙e帇 tar.gz +func DeCompress(tarFile, dest string) error { + srcFile, err := os.Open(tarFile) + if err != nil { + return err + } + defer srcFile.Close() + gr, err := gzip.NewReader(srcFile) + if err != nil { + return err + } + defer gr.Close() + tr := tar.NewReader(gr) + for { + hdr, err := tr.Next() + if err != nil { + if err == io.EOF { + break + } else { + return err + } + } + filename := dest + hdr.Name + file, err := createFile(filename) + if err != nil { + return err + } + io.Copy(file, tr) + } + return nil +} + +func createFile(name string) (*os.File, error) { + err := os.MkdirAll(string([]rune(name)[0:strings.LastIndex(name, "/")]), 0755) + if err != nil { + return nil, err + } + return os.Create(name) +} + func FormatNum(oNum int,n int) string { m := 0 for { @@ -309,4 +410,20 @@ } fmtStr := "%0"+strconv.Itoa(m)+"d" return fmt.Sprintf(fmtStr, n) +} + +func FileMd5(path string) (string,error){ + file, err := os.Open(path) + if err !=nil { + return "",err + } + + defer file.Close() + + _md5 := md5.New() + if _,err := io.Copy(_md5, file);err != nil { + return "",err + } + + return hex.EncodeToString(_md5.Sum(nil)),nil } \ No newline at end of file -- Gitblit v1.8.0