Home > Backend Development > Golang > How to Zip Folder Content in Go Without Including the Root Folder?

How to Zip Folder Content in Go Without Including the Root Folder?

Mary-Kate Olsen
Release: 2024-11-17 21:46:01
Original
797 people have browsed it

How to Zip Folder Content in Go Without Including the Root Folder?

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))
}
Copy after login

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)
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template