Home >Backend Development >Golang >How to Zip Directory Contents Excluding the Root Folder?

How to Zip Directory Contents Excluding the Root Folder?

Linda Hamilton
Linda HamiltonOriginal
2024-11-18 22:17:02382browse

How to Zip Directory Contents Excluding the Root Folder?

How to Zip Directory Contents Excluding Root Folder

Question:

You have a directory structure like this:

dir1
  file1.html
  file2.go

When you zip it to dir1.zip and extract it, you get the same structure:

dir1
  file1.html
  file2.go

However, you want to zip the content inside "dir1" without the root folder "dir1" as a result after extracting.

Answer:

To achieve this, modify the code in your Zipit function. Specifically, examine the following code:

if baseDir != "" {
    header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}

This code adds the base directory (in this case, "dir1") to the filename inside the archive. To exclude the root folder from the extracted content, simply remove the addition of the base directory:

header.Name = strings.TrimPrefix(path, source)

This code trims the prefix from the path and assigns it to the header name without including the base directory.

Example:

If you're calling your function as follows:

Zipit("dir1/", "dir1.zip")

After making the code modification, your extracted content will be:

file1.html
file2.go

without the "dir1" root folder.

Other Notes:

  • It's worth noting that this modification affects the filename within the archive, not the actual content of the files.
  • You can experiment with other filepath functions to further customize the filename as desired.

The above is the detailed content of How to Zip Directory Contents Excluding the Root Folder?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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