How to extract files from a tarball archive in Go?

To extract files from a tarball archive in Go, you can use the archive/tar package along with the compress/gzip package to handle both the tarball and gzip compression.

Here's an example code snippet that demonstrates the extraction process:

package main import ( "archive/tar" "compress/gzip" "fmt" "io" "log" "os" ) func main() { // Open the tarball file, err := os.Open("archive.tar.gz") if err != nil { log.Fatal(err) } defer file.Close() // Create a gzip reader to decompress the tarball gzipReader, err := gzip.NewReader(file) if err != nil { log.Fatal(err) } defer gzipReader.Close() // Create a tar reader to extract files from the decompressed tarball tarReader := tar.NewReader(gzipReader) // Iterate over each file in the tarball for { header, err := tarReader.Next() if err == io.EOF { // Reached end of the tarball break } if err != nil { log.Fatal(err) } // Create the file on disk targetFile, err := os.Create(header.Name) if err != nil { log.Fatal(err) } defer targetFile.Close() // Copy the contents of the current file to the disk _, err = io.Copy(targetFile, tarReader) if err != nil { log.Fatal(err) } fmt.Printf("Extracted: %s\n", header.Name) } }

Make sure to replace "archive.tar.gz" with the path to your tarball archive file. The code will extract all the files from the tarball and save them in the current directory.

Note: This example assumes that the tarball is compressed using gzip. If your tarball is compressed using a different method like bzip2 or xz, you'll need to modify the code accordingly.