SoFunction
Updated on 2025-04-13

Detailed explanation of how to efficiently decompress ZIP files in Go language

In daily development, we often need to process ZIP files, such as decompressing, backing up data, or processing log files after downloading compressed packages from remote servers. In this article, we will introduce an efficient ZIP file decompression tool written in Go and provide sample code to help you get started quickly.

Code implementation

The following isUnzipThe complete implementation of the function, which can decompress the ZIP file to the specified directory and return the list of decompressed file paths.

package utils

import (
	"archive/zip"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
)

// Unzip unzip the ZIP file to the specified directoryfunc Unzip(zipFile string, destDir string) ([]string, error) {
	zipReader, err := (zipFile)
	var paths []string
	if err != nil {
		return []string{}, err
	}
	defer ()

	for _, f := range  {
		if (, "..") > -1 {
			return []string{}, ("%s file name is illegal", )
		}
		fpath := (destDir, )
		paths = append(paths, fpath)
		if ().IsDir() {
			(fpath, )
		} else {
			if err = ((fpath), ); err != nil {
				return []string{}, err
			}

			inFile, err := ()
			if err != nil {
				return []string{}, err
			}
			defer ()

			outFile, err := (fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, ())
			if err != nil {
				return []string{}, err
			}
			defer ()

			_, err = (outFile, inFile)
			if err != nil {
				return []string{}, err
			}
		}
	}
	return paths, nil
}

Example of usage

existIn the file, we can useUnzipMethod to decompress the ZIP file.

package main

import (
	"fmt"
	"log"
	"utils"
)

func main() {
	zipFile := ""  // ZIP file that needs to be decompressed	destDir := "output"        // Unzip the target directory
	files, err := (zipFile, destDir)
	if err != nil {
		("Decompression failed: %v", err)
	}

	("Decompress successfully, file list:")
	for _, file := range files {
		(file)
	}
}

Code parsing

  • Open a ZIP file(zipFile)Used to open a ZIP file.
  • Traversing ZIP internal files:usefor _, f := range Iterates through all files within the ZIP.
  • Safety check:pass(, "..")Prevent path traversal attacks.
  • Create directories and files:useCreate necessary folders and useCreate a file.
  • File Copy(outFile, inFile)Copy the file contents.

Summarize

ShouldUnzipThe method is an efficient and secure ZIP file decompression tool suitable for a variety of scenarios such as file backup, log decompression and data processing. You can expand features according to your needs, such as password-protected ZIP files, progress bar display, etc.

This is the end of this article about how to effectively decompress ZIP files in Go. For more relevant content on Go decompression ZIP, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!