Logo

Programming-Idioms

History of Idiom 217 > diff from v2 to v3

Edit summary for version 3 by programming-idioms.org:
New Go implementation by user [programming-idioms.org]

Version 2

2019-12-16, 17:42:33

Version 3

2019-12-17, 15:55:10

Idiom #217 Create a Zip archive

Create a zip-file with filename name and add the files listed in list to that zip-file.

Idiom #217 Create a Zip archive

Create a zip-file with filename name and add the files listed in list to that zip-file.

Extra Keywords
zip
Extra Keywords
zip
Imports
import "archive/zip"
import "bytes"
import "os"
import "io"
import "io/ioutil"
Code
buf := new(bytes.Buffer)
w := zip.NewWriter(buf)
for _, filename := range list {
	input, err := os.Open(filename)
	if err != nil {
		return err
	}
	output, err := w.Create(filename)
	if err != nil {
		return err
	}
	_, err = io.Copy(output, input)
	if err != nil {
		return err
	}
}

err := w.Close()
if err != nil {
	return err
}

err = ioutil.WriteFile(name, buf.Bytes(), 0777)
if err != nil {
	return err
}
Comments bubble
list contains filenames of files existing in the filesystem.
In this example, the zip data is buffered in memory before writing to the filesystem.
Doc URL
https://golang.org/pkg/archive/zip/
Origin
https://golang.org/pkg/archive/zip/#example_Writer
Demo URL
https://play.golang.org/p/EwTobQsjKz4