To create a compressed tarball archive from a directory in Go, you can use the archive/tar
and compress/gzip
packages. Here's an example code to accomplish this:
package main
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"path/filepath"
)
func createTarball(source, target string) error {
// Create the target file
targetFile, err := os.Create(target)
if err != nil {
return err
}
defer targetFile.Close()
// Create a gzip writer
gzw := gzip.NewWriter(targetFile)
defer gzw.Close()
// Create a tar writer
tw := tar.NewWriter(gzw)
defer tw.Close()
// Walk through the source directory and add files to the archive
err = filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Get the file header
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
// Update the header name with the relative path
relPath, err := filepath.Rel(source, path)
if err != nil {
return err
}
header.Name = relPath
// Write the header to the tarball
err = tw.WriteHeader(header)
if err != nil {
return err
}
// If the file is not a directory, write its contents to the tarball
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tw, file)
if err != nil {
return err
}
}
return nil
})
return err
}
func main() {
source := "/path/to/source/directory"
target := "/path/to/target/archive.tar.gz"
err := createTarball(source, target)
if err != nil {
panic(err)
}
}
Make sure to replace /path/to/source/directory
with the actual path of the directory you want to archive, and /path/to/target/archive.tar.gz
with the desired path of the resulting tarball archive.