1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
func Zipit(source, target, filter string) error { var err error if isAbs := filepath.IsAbs(source); !isAbs { source, err = filepath.Abs(source) if err != nil { return errors.WithStack(err) } } zipfile, err := os.Create(target) if err != nil { return errors.WithStack(err) }
defer func() { if err := zipfile.Close(); err != nil{ log.Slogger.Errorf("*File close error: %s, file: %s", err.Error(), zipfile.Name()) } }()
zw := zip.NewWriter(zipfile)
defer func() { if err := zw.Close(); err != nil{ log.Slogger.Errorf("zipwriter close error: %s", err.Error()) } }()
info, err := os.Stat(source) if err != nil { return errors.WithStack(err) }
var baseDir string if info.IsDir() { baseDir = filepath.Base(source) }
err = filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil { return errors.WithStack(err) }
ism, err := filepath.Match(filter, info.Name())
if err != nil { return errors.WithStack(err) } if ism { return nil } header, err := zip.FileInfoHeader(info) if err != nil { return errors.WithStack(err) }
if baseDir != "" { header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) }
if info.IsDir() { header.Name += "/" } else { header.Method = zip.Deflate } writer, err := zw.CreateHeader(header) if err != nil { return errors.WithStack(err) }
if info.IsDir() { return nil } file, err := os.Open(path) if err != nil { return errors.WithStack(err) }
defer func() { if err := file.Close(); err != nil{ log.Slogger.Errorf("*File close error: %s, file: %s", err.Error(), file.Name()) } }() _, err = io.Copy(writer, file)
return errors.WithStack(err) })
if err != nil { return errors.WithStack(err) }
return nil }
|