Zipping files is a common operation when you need to archive or compress data. The Go programming language offers a powerful package, archive/zip, which allows you to create and extract zip files efficiently. In this article, we will walk through how to create and handle ZIP files using this package.
Creating a ZIP File
To start creating a ZIP file, you need to import the archive/zip package along with other necessary packages such as os and io. Below is a simple example of how to create a ZIP file.
package main
import (
"archive/zip"
"fmt"
"os"
)
func main() {
newZipFile, err := os.Create("example.zip")
if err != nil {
fmt.Println(err)
return
}
defer newZipFile.Close()
zipWriter := zip.NewWriter(newZipFile)
defer zipWriter.Close()
// Add files to the ZIP file here
addFile(zipWriter, "file1.txt")
addFile(zipWriter, "file2.txt")
}
func addFile(zipWriter *zip.Writer, filename string) {
fileToZip, err := os.Open(filename)
if err != nil {
fmt.Println(err)
return
}
defer fileToZip.Close()
w, err := zipWriter.Create(filename)
if err != nil {
fmt.Println(err)
return
}
if _, err := io.Copy(w, fileToZip); err != nil {
fmt.Println(err)
}
}
In the above example, we created a new ZIP writer object and added two text files (file1.txt and file2.txt) into the zip archive.
Extracting ZIP Files
Extracting files from a ZIP archive is another useful operation. Here is an example of how to open and extract files:
package main
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
)
func main() {
reader, err := zip.OpenReader("example.zip")
if err != nil {
fmt.Println(err)
return
}
defer reader.Close()
for _, file := range reader.File {
fmt.Printf("Extracting file: %s\n", file.Name)
err := extractFile(file)
if err != nil {
fmt.Println(err)
}
}
}
func extractFile(f *zip.File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
path := filepath.Join("output", f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(path, os.ModePerm)
} else {
os.MkdirAll(filepath.Dir(path), os.ModePerm)
outFile, err := os.Create(path)
if err != nil {
return err
}
defer outFile.Close()
_, err = io.Copy(outFile, rc)
}
return err
}
This code snippet shows how to iterate over each file in a ZIP archive and extract it to a designated directory while preserving the file structure.
Conclusion
In this article, we discussed two core operations of handling ZIP files in Go using the archive/zip package: creating a ZIP file and extracting files from a ZIP archive. With these tools, you'll be able to compress and decompress file data effortlessly in your Go applications.