Sling Academy
Home/Golang/How to Create and Handle ZIP Files in Go with `archive/zip`

How to Create and Handle ZIP Files in Go with `archive/zip`

Last updated: November 27, 2024

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.

Next Article: Generating Random Numbers and Strings Using `math/rand`

Previous Article: Data Validation and Sanitization with `validator` in Go

Series: Go Utilities and Tools

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant