Home >Backend Development >Golang >How to Easily Unzip Files in Go with the `zip` Package?
Unzipping Made Easy with Go
Unzipping files in Go is a breeze with the zip package. Its simplicity allows you to create a utility function like this:
func Unzip(src, dest string) error { r, err := zip.OpenReader(src) if err != nil { return err } defer func() { if err := r.Close(); err != nil { panic(err) } }() os.MkdirAll(dest, 0755) // Closure isolates file descriptor .Close() calls extractAndWriteFile := func(f *zip.File) error { rc, err := f.Open() if err != nil { return err } defer func() { if err := rc.Close(); err != nil { panic(err) } }() path := filepath.Join(dest, f.Name) // Prevent ZipSlip vulnerability if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) { return fmt.Errorf("illegal file path: %s", path) } if f.FileInfo().IsDir() { os.MkdirAll(path, f.Mode()) } else { os.MkdirAll(filepath.Dir(path), f.Mode()) f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } defer func() { if err := f.Close(); err != nil { panic(err) } }() _, err = io.Copy(f, rc) if err != nil { return err } } return nil } for _, f := range r.File { err := extractAndWriteFile(f) if err != nil { return err } } return nil }
This code meticulously iterates over each file in the zip archive, handling directories and regular files appropriately while ensuring filepath validity. Note that the closure approach eliminates unnecessary defer stacking, enhances encapsulation, and streamlines error handling.
The above is the detailed content of How to Easily Unzip Files in Go with the `zip` Package?. For more information, please follow other related articles on the PHP Chinese website!