Skip to content

Instantly share code, notes, and snippets.

@fachryansyah
Last active December 10, 2019 09:42
Show Gist options
  • Save fachryansyah/625cee1089906df0d47332d4fdadd33a to your computer and use it in GitHub Desktop.
Save fachryansyah/625cee1089906df0d47332d4fdadd33a to your computer and use it in GitHub Desktop.
/*
HOW TO USE
zipFile( FOLDER-WANT-TO-ZIP, TARGET-DIRECTORY )
PACKAGE : archive/zip
*/
func zipFile(source, target string) error {
zipfile, err := os.Create(target)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
info, err := os.Stat(source)
if err != nil {
return nil
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(source)
}
filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
})
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment