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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-18 05:03:02748browse

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

Zipping Content within a Folder without the Root Folder

The requirement is to create a ZIP file containing the files within a directory, excluding the directory itself as the root folder upon extraction.

The provided snippet attempts to achieve this by setting the header name using the following line:

header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))

However, this code adds the base directory (e.g., "dir1") to the header name, resulting in an archive where the files are nested within the directory structure.

To address this issue, the line should be replaced with the following:

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

This removes the base directory from the header name, ensuring that the files are extracted without the directory structure.

The modified code would look like this:

import (
    "archive/zip"
    "fmt"
    "io"
    "os"
    "path/filepath"
)

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
    }

    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
        }

        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
}

func main() {
    err := Zipit("path/dir1" +"/", "test"+".zip")
    if err != nil {
        fmt.Println(err)
    }
}

This code effectively zips the content within the "dir1" directory without including the directory itself in the ZIP file.

The above is the detailed content of How to Zip Folder Content Without the Root Folder in Go?. 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