package main import ( "archive/tar" "fmt" "io" "os" ) func main() { file, err := os.Open("example.tar") if err != { fmt.Println(err) return } defer file.Close() tarReader := tar.NewReader(file) for { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { fmt.Println(err) return } fmt.Println(header.Name) } }
package main import ( "archive/tar" "fmt" "io" "os" ) func main() { file, err := os.Open("example.tar") if err != nil { fmt.Println(err) return } defer file.Close() tarReader := tar.NewReader(file) for { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { fmt.Println(err) return } if header.Typeflag == tar.TypeDir { err := os.MkdirAll(header.Name, 0755) if err != nil { fmt.Println(err) return } continue } outFile, err := os.Create(header.Name) if err != nil { fmt.Println(err) return } defer outFile.Close() if _, err = io.Copy(outFile, tarReader); err != nil { fmt.Println(err) return } } }This example opens a tar archive "example.tar", reads its contents with `tar.NewReader` function, and creates a new file for each entry in the archive with `os.Create` function. If the entry is a directory, it creates the directory using `os.MkdirAll`. If it's a file, it copies the contents from the archive to the newly created file using `io.Copy` function. In summary, the go archive/tar package provides functions for reading and writing tar archive files and is useful for compressing and decompressing files.