Skip to content

Instantly share code, notes, and snippets.

@kjk
Last active June 29, 2020 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjk/efa13acbaa94b10c35c83b498e7c9edf to your computer and use it in GitHub Desktop.
Save kjk/efa13acbaa94b10c35c83b498e7c9edf to your computer and use it in GitHub Desktop.
Create ZIP file in Go (made with https://codeeval.dev)

Creating ZIP archives in Go

Go standard library has archive/zip package for reading and creating ZIP archives.

package main
import (
"archive/zip"
"fmt"
"io"
"log"
"os"
"path/filepath"
)
func zipAddFile(zw *zip.Writer, filePath string, pathInZip string) error {
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
if pathInZip == "" {
pathInZip = filepath.Base(filePath)
}
w, err := zw.Create(pathInZip)
if err != nil {
return err
}
_, err = io.Copy(w, f)
return err
}
func main() {
fw, err := os.Create("out.zip")
if err != nil {
log.Fatalf("os.Create() failed with '%s'\n", err)
}
zw := zip.NewWriter(fw)
err = zipAddFile(zw, "create_zip_file.go", "")
if err != nil {
log.Fatalf("zipAddFile() failed with '%s'\n", err)
}
err = zipAddFile(zw, "create_zip_file.go", "another copy.go")
if err != nil {
log.Fatalf("zipAddFile() failed with '%s'\n", err)
}
_ = zw.Close()
_ = fw.Close()
printFileName("out.zip")
}
func printFileName(filePath string) {
st, _ := os.Stat(filePath)
fmt.Printf("Size of file '%s' is %d bytes\n", filePath, st.Size())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment