Skip to content

Go: Create Zip files

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 (

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 := ""

	// Create a new zip file
	newZipFile, err := os.Create(zipFileName)
	if err != nil {
		fmt.Println("Error creating zip file:", err)
	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)
	defer fileToZip.Close()

	// Create a file header
	info, err := fileToZip.Stat()
	if err != nil {
		fmt.Println("Error getting file info:", err)

	header, err := zip.FileInfoHeader(info)
	if err != nil {
		fmt.Println("Error creating file header:", err)

	// 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)

	// Copy file data to zip writer
	_, err = io.Copy(writer, fileToZip)
	if err != nil {
		fmt.Println("Error copying file data to zip:", err)

This Go code demonstrates how to create a zip file named 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.
0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments