Skip to content

Instantly share code, notes, and snippets.

@evzpav
Last active August 24, 2020 21:57
Show Gist options
  • Save evzpav/ae5116c466ea90e0e1b6196fec3edd12 to your computer and use it in GitHub Desktop.
Save evzpav/ae5116c466ea90e0e1b6196fec3edd12 to your computer and use it in GitHub Desktop.
package main
import (
"archive/zip"
"fmt"
"io/ioutil"
"os"
)
func main() {
ZipFolder("myfiles")
}
func ZipFolder(sourceFolder string) {
// Get a Buffer to Write To
outFile, err := os.Create(sourceFolder + ".zip")
if err != nil {
fmt.Println(err)
}
defer outFile.Close()
// Create a new zip archive.
w := zip.NewWriter(outFile)
// Add some files to the archive.
addFiles(w, sourceFolder+"/", "")
// Make sure to check the error on Close.
if err = w.Close(); err != nil {
fmt.Println(err)
}
}
func addFiles(w *zip.Writer, basePath, baseInZip string) {
// Open the Directory
files, err := ioutil.ReadDir(basePath)
if err != nil {
fmt.Println(err)
return
}
for _, file := range files {
fmt.Println(basePath + file.Name())
if file.IsDir() {
// Recurse
newBase := basePath + file.Name() + "/"
fmt.Println("Recursing and Adding SubDir: " + file.Name())
fmt.Println("Recursing and Adding SubDir: " + newBase)
addFiles(w, newBase, baseInZip+file.Name()+"/")
continue
}
zipFile(w, file, basePath, baseInZip)
}
}
func zipFile(w *zip.Writer, file os.FileInfo, basePath, baseInZip string) {
dat, err := ioutil.ReadFile(basePath + file.Name())
if err != nil {
fmt.Println(err)
return
}
// Add some files to the archive.
f, err := w.Create(baseInZip + file.Name())
if err != nil {
fmt.Println(err)
return
}
_, err = f.Write(dat)
if err != nil {
fmt.Println(err)
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment