1

I am trying to create a .tar.gz file from folder that contains multiple files / folders. Once the .tar.gz file gets created, while extracting, the files are not not properly extracted. Mostly I think its because of large names or path exceeding some n characters, because same thing works when the filename/path is small. I referred this https://github.com/golang/go/issues/17630 and tried to add below code but it did not help.

header.Uid = 0
header.Gid = 0

I am using simple code seen below to create .tar.gz. The approach is, I create a temp folder, do some processing on the files and from that temp path, I create the .tar.gz file hence in the path below I am using pre-defined temp folder path.

package main

import (
    "archive/tar"
    "compress/gzip"
    "fmt"
    "io"
    "log"
    "os"
    fp "path/filepath"
)

func main() {

    // Create output file
    out, err := os.Create("output.tar.gz")
    if err != nil {
        log.Fatalln("Error writing archive:", err)
    }
    defer out.Close()

    // Create the archive and write the output to the "out" Writer
    tmpDir := "C:/Users/USERNAME~1/AppData/Local/Temp/temp-241232063"
    err = createArchive1(tmpDir, out)
    if err != nil {
        log.Fatalln("Error creating archive:", err)
    }

    fmt.Println("Archive created successfully")
}

func createArchive1(path string, targetFile *os.File) error {
    gw := gzip.NewWriter(targetFile)
    defer gw.Close()

    tw := tar.NewWriter(gw)
    defer tw.Close()

    // walk through every file in the folder
    err := fp.Walk(path, func(filePath string, info os.FileInfo, err error) error {
        // ensure the src actually exists before trying to tar it
        if _, err := os.Stat(filePath); err != nil {
            return err
        }

        if err != nil {
            return err
        }

        if info.IsDir() {
            return nil
        }

        file, err := os.Open(filePath)
        if err != nil {
            return err
        }
        defer file.Close()


        // generate tar header
        header, err := tar.FileInfoHeader(info, info.Name())
        header.Uid = 0
        header.Gid = 0
        if err != nil {
            return err
        }

        header.Name = filePath //strings.TrimPrefix(filePath, fmt.Sprintf("%s/", fp.Dir(path))) //info.Name()

        // write header
        if err := tw.WriteHeader(header); err != nil {
            return err
        }

        if _, err := io.Copy(tw, file); err != nil {
            return err
        }

        return nil
    })
    return err
}

Please let me know what wrong I am doing.

Sachin Kadam
  • 265
  • 2
  • 12

0 Answers0