To create a tarball (tar.gz) archive from files and directories in Go, you can use the archive/tar
and compress/gzip
packages. The following code snippet demonstrates how to create a tarball containing multiple files and directories:
package main
import (
"archive/tar"
"compress/gzip"
"io"
"log"
"os"
"path/filepath"
)
func main() {
outputFile, err := os.Create("archive.tar.gz")
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
gzipWriter := gzip.NewWriter(outputFile)
defer gzipWriter.Close()
tarWriter := tar.NewWriter(gzipWriter)
defer tarWriter.Close()
files := []string{
"file1.txt",
"file2.txt",
"directory1/",
"directory2/",
}
for _, file := range files {
if err := addFileToTarball(file, tarWriter); err != nil {
log.Println(err)
}
}
}
func addFileToTarball(file string, tarWriter *tar.Writer) error {
// Open the file or directory
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
// Get file information
info, err := f.Stat()
if err != nil {
return err
}
// Create header for the file or directory
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
// Write header to tarball
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
// If the file is a regular file, write its contents
if !info.IsDir() {
_, err = io.Copy(tarWriter, f)
if err != nil {
return err
}
}
// If the file is a directory, recursively add its contents
if info.IsDir() {
files, err := f.Readdir(-1)
if err != nil {
return err
}
for _, file := range files {
filePath := filepath.Join(file.Name())
if err := addFileToTarball(filePath, tarWriter); err != nil {
log.Println(err)
}
}
}
return nil
}
In this code, you need to specify the files and directories you want to include in the tarball by populating the files
slice. The addFileToTarball
function is a recursive function that adds files and directories to the tarball. It uses the archive/tar
package to create the tarball file structure and the compress/gzip
package to compress the tarball. Finally, it writes the tarball to a file called archive.tar.gz
.