Zipping Content from Folder Excluding Root Folder
In Go, zipping the content within a directory while excluding the root folder can be achieved using zip.Writer.
Issue Description
The original code aims to zip the contents of a directory ("dir1") into "dir1.zip". However, upon extraction, the zipped files retain the "dir1" folder structure as their root. The goal is to eliminate the root folder upon extraction.
Solution
To achieve this, we need to modify the header.Name field within the zip.Writer. This field determines the name of the file within the archive. In the original code, the field is set as follows:
if baseDir != "" { header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) }
This code ensures that the filename includes the baseDir ("dir1") and the file's path relative to the source directory ("path/dir1"). However, to remove the root folder after extraction, we need to omit the baseDir:
header.Name = strings.TrimPrefix(path, source)
With this modification, the zipped files will be directly under the root of the archive, and they will not have the "dir1" folder as their root upon extraction.
Result
By omitting the baseDir from the header.Name field, the content of the "dir1" directory will be zipped into "dir1.zip" without the root folder. This allows the user to extract the files directly without having to navigate through the "dir1" folder.
The above is the detailed content of How to Zip Folder Content in Go Without Including the Root Folder?. For more information, please follow other related articles on the PHP Chinese website!