Browse Source

[utils/zipfiles.go]: 解决for循环中使用defer可能会造成的内存泄露问题

main
golyu 4 years ago
parent
commit
959b69d99a
  1. 31
      server/utils/zipfiles.go

31
server/utils/zipfiles.go

@ -13,28 +13,34 @@ import (
//@param: filename string, files []string, oldform, newform string
//@return: error
func ZipFiles(filename string, files []string, oldform, newform string) error {
func ZipFiles(filename string, files []string, oldForm, newForm string) error {
newZipFile, err := os.Create(filename)
if err != nil {
return err
}
defer newZipFile.Close()
defer func() {
_ = newZipFile.Close()
}()
zipWriter := zip.NewWriter(newZipFile)
defer zipWriter.Close()
defer func() {
_ = zipWriter.Close()
}()
// 把files添加到zip中
for _, file := range files {
zipfile, err := os.Open(file)
zipFile, err := os.Open(file)
if err != nil {
return err
}
defer zipfile.Close()
err = func() error {
defer func() {
_ = zipFile.Close()
}()
// 获取file的基础信息
info, err := zipfile.Stat()
info, err := zipFile.Stat()
if err != nil {
return err
}
@ -44,8 +50,8 @@ func ZipFiles(filename string, files []string, oldform, newform string) error {
return err
}
// 使用上面的FileInforHeader() 就可以把文件保存的路径替换成我们自己想要的了,如下面
header.Name = strings.Replace(file, oldform, newform, -1)
// 使用上面的FileInfoHeader() 就可以把文件保存的路径替换成我们自己想要的了,如下面
header.Name = strings.Replace(file, oldForm, newForm, -1)
// 优化压缩
// 更多参考see http://golang.org/pkg/archive/zip/#pkg-constants
@ -55,7 +61,12 @@ func ZipFiles(filename string, files []string, oldform, newform string) error {
if err != nil {
return err
}
if _, err = io.Copy(writer, zipfile); err != nil {
if _, err = io.Copy(writer, zipFile); err != nil {
return err
}
return nil
}()
if err != nil {
return err
}
}

Loading…
Cancel
Save