In Go, you can create zip files using the archive/zip
package. Here’s an example of how to create a zip file containing multiple files
package main
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
)
func main() {
// List of file paths to include in the zip
filesToZip := []string{"file1.txt", "file2.txt", "folder/file3.txt"}
// Name for the resulting zip file
zipFileName := "my_archive.zip"
// Create a new zip file
newZipFile, err := os.Create(zipFileName)
if err != nil {
fmt.Println("Error creating zip file:", err)
return
}
defer newZipFile.Close()
// Create a new zip writer
zipWriter := zip.NewWriter(newZipFile)
defer zipWriter.Close()
// Add each file to the zip
for _, file := range filesToZip {
addFileToZip(file, zipWriter)
}
fmt.Println("Zip file created:", zipFileName)
}
func addFileToZip(filePath string, zw *zip.Writer) {
fileToZip, err := os.Open(filePath)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer fileToZip.Close()
// Create a file header
info, err := fileToZip.Stat()
if err != nil {
fmt.Println("Error getting file info:", err)
return
}
header, err := zip.FileInfoHeader(info)
if err != nil {
fmt.Println("Error creating file header:", err)
return
}
// Change to relative path for the zip file
header.Name = filepath.Base(filePath)
// Add file header to the zip
writer, err := zw.CreateHeader(header)
if err != nil {
fmt.Println("Error creating file in zip:", err)
return
}
// Copy file data to zip writer
_, err = io.Copy(writer, fileToZip)
if err != nil {
fmt.Println("Error copying file data to zip:", err)
return
}
}
This Go code demonstrates how to create a zip file named my_archive.zip
containing the specified files (file1.txt
, file2.txt
, folder/file3.txt
).
- The
addFileToZip
function handles adding each file to the zip. It opens the file, creates a file header, adds the file header to the zip, and copies the file data into the zip. - Ensure you have appropriate permissions to access the files you want to zip and write permissions in the directory where you plan to create the zip file.
- Also, remember to handle errors appropriately in your actual implementation.