Home >Backend Development >Golang >How to Zip a Directory in Go Without Including the Root Folder?
Zipping Content Without the Root Folder
In Go, when zipping a directory, it's common to include the root folder as part of the archive. However, there are scenarios where you may want to exclude the root folder to ensure that only the contents are extracted.
To achieve this, the Zipit function you've provided requires a small modification:
header.Name = strings.TrimPrefix(path, source)
In the original code, the line header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) adds the base directory name (e.g., "dir1") to the filename within the archive. By replacing this with the code above, the base directory name is omitted.
As a result, when you extract the ".zip" file, you'll obtain the contents without the "dir1" folder as the root directory.
// Modified Zipit function func Zipit(source, target string) error { zipfile, err := os.Create(target) if err != nil { return err } defer zipfile.Close() archive := zip.NewWriter(zipfile) defer archive.Close() info, err := os.Stat(source) if err != nil { return nil } // Remove the base directory name filepath.Walk(source, func(path string, info os.FileInfo, err error) error { if err != nil { return err } header, err := zip.FileInfoHeader(info) if err != nil { return err } // Trim the base directory name from the filename header.Name = strings.TrimPrefix(path, source) if info.IsDir() { header.Name += "/" } else { header.Method = zip.Deflate } writer, err := archive.CreateHeader(header) if err != nil { return err } if info.IsDir() { return nil } file, err := os.Open(path) if err != nil { return err } defer file.Close() _, err = io.Copy(writer, file) return err }) return err }
Now, when you call Zipit using:
Zipit("dir1/", "dir1.zip")
The resulting ".zip" file will contain only the contents of "dir1" without the "dir1" folder as the root directory upon extraction.
The above is the detailed content of How to Zip a Directory in Go Without Including the Root Folder?. For more information, please follow other related articles on the PHP Chinese website!