1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
zip.go 2.36 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-09-03 16:54 . build
package archive
import (
"archive/zip"
"bytes"
"gitee.com/h79/goutils/common/file"
fileconfig "gitee.com/h79/goutils/common/file/config"
"io"
"os"
"path/filepath"
"strings"
)
func IsZip(zipPath string) bool {
f, err := os.Open(zipPath)
if err != nil {
return false
}
defer f.Close()
buf := make([]byte, 4)
if n, err := f.Read(buf); err != nil || n < 4 {
return false
}
return bytes.Equal(buf, []byte("PK\x03\x04"))
}
func UnZipFile(archive, target string, stream ...fileconfig.WriteStream) error {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}
defer reader.Close()
for i := range reader.File {
f := reader.File[i]
path := filepath.Join(target, f.Name)
if f.FileInfo().IsDir() {
if err := os.MkdirAll(path, f.Mode()); err != nil {
return err
}
continue
}
fileReader, err := f.Open()
if err != nil {
return err
}
targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
_ = fileReader.Close()
return err
}
if _, err := io.Copy(targetFile, fileReader); err != nil {
_ = targetFile.Close()
_ = fileReader.Close()
return err
}
for j := range stream {
stream[j].OnWriter(targetFile)
}
_ = targetFile.Close()
_ = fileReader.Close()
}
return nil
}
func ZipFile(srcPath, destPath string, stream ...fileconfig.ReaderStream) error {
zipFile, err := os.Create(destPath)
if err != nil {
return err
}
defer zipFile.Close()
return ZipWrite(zipFile, srcPath, stream...)
}
func ZipWrite(writer io.Writer, srcPath string, stream ...fileconfig.ReaderStream) error {
archive := zip.NewWriter(writer)
defer archive.Close()
depth := file.WithMaxDepth()
return file.ReadDir(srcPath, &depth, func(path string, isDir bool, entry os.DirEntry) int {
info, err := entry.Info()
if err != nil {
return -1
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return -1
}
header.Name = strings.TrimPrefix(path, srcPath+`/`)
if isDir {
header.Name += `/`
} else {
header.Method = zip.Deflate
}
w, err := archive.CreateHeader(header)
if err != nil {
return -1
}
if isDir {
return 0
}
f, err := os.Open(path)
if err != nil {
return -2
}
defer f.Close()
if ll, err := io.Copy(w, f); err != nil || ll != info.Size() {
return -3
}
for i := range stream {
stream[i].OnReader(f)
}
return 0
})
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.22.7

搜索帮助